language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
Rust
hhvm/hphp/hack/src/hackc/ir/assemble/tokenizer.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::borrow::Cow; use std::fmt; use std::io::BufRead; use std::io::BufReader; use std::io::Read; use std::rc::Rc; use std::sync::Arc; use anyhow::bail; use anyhow::Result; use ffi::Str; use hash::HashSet; use ir_core::StringInterner; use log::trace; use once_cell::sync::OnceCell; use crate::util::unescape; pub(crate) struct Tokenizer<'a> { buf: BufReader<&'a mut dyn Read>, filename: Rc<String>, cur_line: u32, next: Option<Token>, log_next: bool, // The tokenizer doesn't need this field but it's a convenient place to // stash it for use by the parser. pub strings: Arc<StringInterner>, } impl<'a> Tokenizer<'a> { pub fn new(read: &'a mut dyn Read, filename: &'a str, strings: Arc<StringInterner>) -> Self { Tokenizer { buf: BufReader::new(read), cur_line: 1, filename: Rc::new(filename.to_string()), log_next: true, next: None, strings, } } fn peek_any_byte(&mut self) -> Result<Option<u8>> { let buf = self.buf.fill_buf()?; if log::log_enabled!(log::Level::Trace) && self.log_next { self.log_next = false; let pos = buf.iter().position(|c| *c == b'\n'); let end = pos.unwrap_or(buf.len()); let ext = if pos.is_some() { "" } else { "..." }; let line = &buf[..end]; trace!("INPUT: {}{ext}", String::from_utf8_lossy(line)); } Ok(buf.first().copied()) } fn peek_non_eol_byte(&mut self) -> Result<Option<u8>> { let b = self.peek_any_byte()?; if let Some(b) = b { if b == b'\n' { Ok(None) } else { Ok(Some(b)) } } else { Ok(None) } } fn cur_line(&self) -> LineNum { LineNum(self.cur_line) } fn consume_any_byte(&mut self) { if log::log_enabled!(log::Level::Trace) { if self.buf.buffer()[0] == b'\n' { self.log_next = true; } } self.buf.consume(1); } fn consume_byte(&mut self) { debug_assert!(self.buf.buffer()[0] != b'\n'); self.consume_any_byte(); } fn read_any_byte(&mut self) -> Result<Option<u8>> { let b = self.peek_any_byte()?; if b.is_some() { self.consume_any_byte(); } Ok(b) } fn raw_read_token(&mut self) -> Result<Option<Token>> { loop { if let Some(first) = self.read_any_byte()? { let cur_loc = self.peek_loc(); let result = match first { b'\n' => { self.cur_line += 1; Token::Eol(cur_loc) } _ if first.is_ascii_whitespace() => { continue; } b'\"' | b'\'' => return Ok(Some(self.read_quoted_string(first, cur_loc)?)), b'.' | b'%' | b'#' => { // A couple tokens are a little special because they could be operator-like or identifier-like. // Ex. '.' could be ".srcloc", ".=" let c = self.peek_any_byte()?; match c { Some(c) if c.is_ascii_alphanumeric() => { self.read_identifier(first, cur_loc)? } _ => self.read_operator(first, cur_loc)?, } } b'-' if self.peek_any_byte()?.map_or(false, |c| c.is_ascii_digit()) => { self.read_number(first, cur_loc)? } b'0' | b'1' | b'2' | b'3' | b'4' | b'5' | b'6' | b'7' | b'8' | b'9' => { self.read_number(first, cur_loc)? } ch if operator_lead_bytes()[ch as usize] => { self.read_operator(first, cur_loc)? } _ => self.read_identifier(first, cur_loc)?, }; return Ok(Some(result)); } else { return Ok(None); } } } fn fill_token(&mut self) -> Result<()> { if self.next.is_none() { self.next = self.raw_read_token()?; } Ok(()) } pub fn peek_token(&mut self) -> Result<Option<&Token>> { self.fill_token()?; Ok(self.next.as_ref()) } pub fn read_token(&mut self) -> Result<Option<Token>> { self.fill_token()?; Ok(self.next.take()) } fn read_operator(&mut self, first: u8, cur_loc: TokenLoc) -> Result<Token> { // The set of characters that start our two or three-character // operators (so we know we need to look for an extended pattern). // // xx // xxx // ^ - The set of all characters that can appear here. static DOUBLE_LEAD: OnceCell<[bool; 256]> = OnceCell::new(); let double_lead = DOUBLE_LEAD.get_or_init(|| { let mut lead_set = [false; 256]; for s in operators().iter() { if s.len() > 1 { lead_set[s.as_bytes()[0] as usize] = true; } } lead_set }); // The set of second characters that start our three-characters // operators (so we know we need to look for a 3-byte pattern). // // xxx // ^ - The set of all characters that can appear here. static TRIPLE_LEAD: OnceCell<[bool; 256]> = OnceCell::new(); let triple_lead = TRIPLE_LEAD.get_or_init(|| { let mut lead_set = [false; 256]; for s in operators().iter() { if s.len() > 2 { lead_set[s.as_bytes()[1] as usize] = true; } } lead_set }); if double_lead[first as usize] { // It might be a two or three character opcode. if let Some(c1) = self.peek_any_byte()? { let double = [first, c1]; let double = std::str::from_utf8(&double).unwrap(); if operators().contains(double) { self.consume_byte(); if triple_lead[c1 as usize] { // It might be a three character opcode. if let Some(c2) = self.peek_any_byte()? { let triple = [first, c1, c2]; let triple = std::str::from_utf8(&triple)?; if operators().contains(triple) { self.consume_byte(); return Ok(Token::Identifier(triple.to_owned(), cur_loc)); } } } return Ok(Token::Identifier(double.to_owned(), cur_loc)); } } } let single = std::str::from_utf8(std::slice::from_ref(&first))?; Ok(Token::Identifier(single.to_owned(), cur_loc)) } fn read_number(&mut self, first: u8, cur_loc: TokenLoc) -> Result<Token> { let mut value = Vec::new(); value.push(first); while let Some(b) = self.peek_non_eol_byte()? { if b.is_ascii_alphanumeric() || b == b'.' || b == b'+' || b == b'-' { self.consume_byte(); value.push(b); } else { break; } } let value = String::from_utf8(value)?; Ok(Token::Identifier(value, cur_loc)) } fn read_quoted_string(&mut self, first: u8, cur_loc: TokenLoc) -> Result<Token> { let mut value = Vec::new(); let mut escaped = false; loop { let b = if let Some(b) = self.read_any_byte()? { b } else { bail!("Unexpected end of file during quoted string"); }; match b { b'\\' if !escaped => { value.push(b); escaped = true; } b'\n' => { if !escaped { value.push(b); } self.cur_line += 1; escaped = false; } _ => { if b == first && !escaped { break; } value.push(b); escaped = false; } } } let value = String::from_utf8(value)?; Ok(Token::QuotedString(first as char, value, cur_loc)) } fn read_identifier(&mut self, first: u8, cur_loc: TokenLoc) -> Result<Token> { let mut value = Vec::new(); value.push(first); while let Some(b) = self.peek_non_eol_byte()? { if b.is_ascii_alphanumeric() || b == b'$' || b == b'.' || b == b'\\' || b == b'_' { self.consume_byte(); value.push(b); } else { break; } } let value = String::from_utf8(value)?; Ok(Token::Identifier(value, cur_loc)) } } impl Tokenizer<'_> { pub fn expect_any_token(&mut self) -> Result<Token> { if let Some(tok) = self.read_token()? { Ok(tok) } else { bail!("Expected any token at {}", self.cur_line()); } } pub fn expect_eol(&mut self) -> Result<Token> { let t = self.expect_any_token()?; if !t.is_eol() { bail!( "{}[{}] Expected end-of-line but got {t}", self.filename, self.cur_line() ); } Ok(t) } pub fn expect_any_identifier(&mut self) -> Result<Token> { let t = self.expect_any_token()?; if !t.is_any_identifier() { bail!( "{}[{}] Expected identifier but got {t}", self.filename, self.cur_line() ); } Ok(t) } pub fn expect_any_string(&mut self) -> Result<Token> { let t = self.expect_any_token()?; if !t.is_any_string() { bail!( "{}[{}] Expected string but got {t}", self.filename, self.cur_line() ); } Ok(t) } pub fn expect_identifier(&mut self, expect: &str) -> Result<Token> { let t = self.expect_any_token()?; if !t.is_identifier(expect) { bail!( "{}[{}] Expected identifier '{expect}' but got {t}", self.filename, self.cur_line() ); } Ok(t) } } impl Tokenizer<'_> { pub fn peek_loc(&self) -> TokenLoc { TokenLoc { filename: Rc::clone(&self.filename), line: self.cur_line, } } pub fn peek_expect_token(&mut self) -> Result<&Token> { let cur_line = self.cur_line(); if let Some(tok) = self.peek_token()? { Ok(tok) } else { bail!("Expected any token at {}", cur_line); } } } impl Tokenizer<'_> { pub fn peek_if_any_string(&mut self) -> Result<Option<&Token>> { if let Some(t) = self.peek_token()? { if t.is_any_string() { return Ok(Some(t)); } } Ok(None) } pub fn peek_if_any_identifier(&mut self) -> Result<Option<&Token>> { if let Some(t) = self.peek_token()? { if t.is_any_identifier() { return Ok(Some(t)); } } Ok(None) } pub fn peek_if_identifier(&mut self, expect: &str) -> Result<Option<&Token>> { if let Some(t) = self.peek_token()? { if t.is_identifier(expect) { return Ok(Some(t)); } } Ok(None) } } impl Tokenizer<'_> { pub fn peek_is_identifier(&mut self, expect: &str) -> Result<bool> { Ok(self.peek_if_identifier(expect)?.is_some()) } pub fn peek_is_close_operator(&mut self) -> Result<bool> { if let Some(t) = self.peek_token()? { Ok(t.is_close_operator()) } else { Ok(false) } } } impl Tokenizer<'_> { pub fn next_if_predicate<F>(&mut self, f: F) -> Result<Option<Token>> where F: FnOnce(&Token) -> bool, { if let Some(t) = self.peek_token()? { if f(t) { return self.read_token(); } } Ok(None) } pub fn next_if_any_string(&mut self) -> Result<Option<Token>> { Ok(if self.peek_if_any_string()?.is_some() { Some(self.expect_any_token()?) } else { None }) } pub fn next_if_identifier(&mut self, expect: &str) -> Result<Option<Token>> { Ok(if self.peek_if_identifier(expect)?.is_some() { Some(self.expect_any_token()?) } else { None }) } } impl Tokenizer<'_> { pub fn next_is_identifier(&mut self, expect: &str) -> Result<bool> { Ok(self.next_if_identifier(expect)?.is_some()) } } #[derive(Debug, Clone)] pub(crate) struct TokenLoc { filename: Rc<String>, line: u32, } impl TokenLoc { pub(crate) fn bail<'a>(&self, msg: impl Into<Cow<'a, str>>) -> anyhow::Error { anyhow::anyhow!("{}[{}]: {}", self.filename, self.line, msg.into()) } } /// The tokenizer uses a simplified parsing model. Things are either newlines, /// quoted strings or identifiers. There are slight differences to how /// identifiers are parsed based on their lead characters (for example words /// starting with a letter can contain '$' in the middle but words starting with /// a number cannot). See read_identifier(), read_operator() and read_number() /// for the details. #[derive(Debug, Clone)] pub(crate) enum Token { Eol(TokenLoc), QuotedString(char, String, TokenLoc), Identifier(String, TokenLoc), } impl Token { pub fn bail<'a>(&self, msg: impl Into<Cow<'a, str>>) -> anyhow::Error { self.loc().bail(msg) } pub fn identifier(&self) -> &str { self.get_identifier().unwrap() } pub fn get_identifier(&self) -> Option<&str> { match self { Token::Identifier(s, _) => Some(s), _ => None, } } pub fn is_any_identifier(&self) -> bool { matches!(self, Token::Identifier(..)) } pub fn is_eol(&self) -> bool { matches!(self, Token::Eol(..)) } pub fn is_identifier(&self, rhs: &str) -> bool { match self { Token::Identifier(lhs, _) => lhs == rhs, _ => false, } } pub fn is_any_string(&self) -> bool { matches!(self, Token::QuotedString(..)) } fn is_close_operator(&self) -> bool { match *self { Token::Identifier(ref lhs, _) => lhs == "]" || lhs == ")" || lhs == ">", _ => false, } } pub fn loc(&self) -> &TokenLoc { match self { Token::Eol(loc) | Token::QuotedString(_, _, loc) | Token::Identifier(_, loc) => loc, } } pub fn unescaped_string(&self) -> Result<Vec<u8>> { match self { Token::QuotedString(_, value, _) => unescape(value), _ => bail!("String expected not {:?}", self), } } pub fn unescaped_identifier(&self) -> Result<Cow<'_, [u8]>> { match self { Token::Identifier(s, _) => Ok(Cow::Borrowed(s.as_bytes())), Token::QuotedString(..) => Ok(Cow::Owned(self.unescaped_string()?)), _ => bail!("Identifier expected, not {self}"), } } pub fn unescaped_bump_str<'a>(&self, alloc: &'a bumpalo::Bump) -> Result<Str<'a>> { let s = self.unescaped_string()?; Ok(Str::new_slice(alloc, &s)) } } impl fmt::Display for Token { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Token::Eol(_) => write!(f, "newline"), Token::QuotedString(delimiter, s, _) => { write!(f, "{delimiter}{s}{delimiter}") } Token::Identifier(s, _) => { write!(f, "{s}") } } } } #[derive(Debug, Clone, Copy)] pub(crate) struct LineNum(u32); impl fmt::Display for LineNum { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } } /// Operators are only different from identifiers in which consecutive /// characters make up a single token vs being split into multiple tokens. fn operators() -> &'static HashSet<&'static str> { static OPERATORS: OnceCell<HashSet<&'static str>> = OnceCell::new(); OPERATORS.get_or_init(|| { #[rustfmt::skip] let ops: HashSet<&'static str> = [ // length 1 "!", "#", "&", "(", ")", "*", "+", ",", "-", "/", ":", ";", "<", "=", ">", "?", "[", "]", "^", "{", "|", "}", // length 2 "!=", "%=", "&=", "**", "*=", "..", "++", "+=", "--", "-=", "->", ".=", "/=", "::", "<<", "<=", "==", "=>", ">=", ">>", "?-", "^=", "|=", // length 3 "!==", "**=", "...", "<<=", "<=>", "===", ">>=", "?->", ].into_iter().collect(); // One weird requirement we have is that the first two bytes of any // triple must be a valid double. This is so we don't ever have to peek // more than 1 character ahead. for op in &ops { assert!( op.len() != 3 || ops.contains(&op[..2]), "Invalid triple header: {op:?}" ); } ops }) } fn operator_lead_bytes() -> &'static [bool; 256] { static LEAD: OnceCell<[bool; 256]> = OnceCell::new(); LEAD.get_or_init(|| { let mut lead_set = [false; 256]; for s in operators().iter() { lead_set[s.as_bytes()[0] as usize] = true; } lead_set }) }
Rust
hhvm/hphp/hack/src/hackc/ir/assemble/util.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use anyhow::bail; use anyhow::Result; pub(crate) fn unescape(string: &str) -> Result<Vec<u8>> { let mut output = Vec::new(); #[derive(Copy, Clone)] enum State { Unescaped, Escaped, Hex0, Hex1(u8), } let mut state = State::Unescaped; for c in string.chars() { match (state, c) { (State::Unescaped, '\\') => { state = State::Escaped; } (State::Unescaped, c) => { output.push(c as u8); } (State::Escaped, 'x') => { state = State::Hex0; } (State::Escaped, '\\') => { state = State::Unescaped; output.push(b'\\'); } (State::Escaped, 'n') => { state = State::Unescaped; output.push(b'\n'); } (State::Escaped, 't') => { state = State::Unescaped; output.push(b'\t'); } (State::Escaped, 'r') => { state = State::Unescaped; output.push(b'\r'); } (State::Escaped, '\"') => { state = State::Unescaped; output.push(b'\"'); } (State::Escaped, _) => { bail!("Bad escape value"); } (State::Hex0, x) if x.is_ascii_hexdigit() => { state = State::Hex1((x.to_digit(16).unwrap() as u8) << 4); } (State::Hex0, _) => { bail!("Bad hex value"); } (State::Hex1(ub), x) if x.is_ascii_hexdigit() => { state = State::Unescaped; output.push(ub + (x.to_digit(16).unwrap() as u8)); } (State::Hex1(_), _) => { bail!("Bad hex value"); } } } Ok(output) }
TOML
hhvm/hphp/hack/src/hackc/ir/cargo/parse_macro/Cargo.toml
# @generated by autocargo [package] name = "parse_macro_ir" version = "0.0.0" edition = "2021" [lib] path = "../../assemble/parse_macro.rs" test = false doctest = false proc-macro = true [dependencies] proc-macro-error = "1.0" proc-macro2 = { version = "1.0.64", features = ["span-locations"] } quote = "1.0.29" [dev-dependencies] macro_test_util = { version = "0.0.0", path = "../../../../utils/test/macro_test_util" }
TOML
hhvm/hphp/hack/src/hackc/ir/conversions/bc_to_ir/Cargo.toml
# @generated by autocargo [package] name = "bc_to_ir" version = "0.0.0" edition = "2021" [lib] path = "lib.rs" [dependencies] b2i_macros = { version = "0.0.0", path = "b2i_macros" } bstr = { version = "1.4.0", features = ["serde", "std", "unicode"] } ffi = { version = "0.0.0", path = "../../../../utils/ffi" } hash = { version = "0.0.0", path = "../../../../utils/hash" } hhbc = { version = "0.0.0", path = "../../../hhbc/cargo/hhbc" } ir = { version = "0.0.0", path = "../.." } itertools = "0.10.3" log = { version = "0.4.17", features = ["kv_unstable", "kv_unstable_std"] } maplit = "1.0" newtype = { version = "0.0.0", path = "../../../../utils/newtype" } once_cell = "1.12"
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/bc_to_ir/class.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use hhbc::Class; use ir::StringInterner; use itertools::Itertools; use crate::convert; use crate::types; pub(crate) fn convert_class<'a>(unit: &mut ir::Unit<'a>, filename: ir::Filename, cls: &Class<'a>) { let constants = cls .constants .as_ref() .iter() .map(|c| crate::constant::convert_constant(c, &unit.strings)) .collect_vec(); let enum_type = cls .enum_type .as_ref() .map(|ty| types::convert_type(ty, &unit.strings)) .into_option(); let enum_includes = cls .enum_includes .iter() .map(|name| ir::ClassId::from_hhbc(*name, &unit.strings)) .collect_vec(); let type_constants = cls .type_constants .iter() .map(|c| convert_type_constant(c, &unit.strings)) .collect(); let ctx_constants = cls.ctx_constants.iter().map(convert_ctx_constant).collect(); let requirements = cls .requirements .as_ref() .iter() .map(|hhbc::Requirement { name, kind }| { let name = ir::ClassId::from_hhbc(*name, &unit.strings); ir::class::Requirement { name, kind: *kind } }) .collect_vec(); let upper_bounds = cls .upper_bounds .iter() .map(|hhbc::UpperBound { name, bounds }| { let tys = (bounds.as_ref().iter()) .map(|ty| types::convert_type(ty, &unit.strings)) .collect_vec(); (*name, tys) }) .collect_vec(); let attributes = cls .attributes .as_ref() .iter() .map(|a| convert::convert_attribute(a, &unit.strings)) .collect_vec(); let base = cls .base .map(|cls| ir::ClassId::from_hhbc(cls, &unit.strings)) .into(); let implements = cls .implements .as_ref() .iter() .map(|interface| ir::ClassId::from_hhbc(*interface, &unit.strings)) .collect_vec(); let properties = cls .properties .as_ref() .iter() .map(|prop| convert_property(prop, &unit.strings)) .collect_vec(); let name = ir::ClassId::from_hhbc(cls.name, &unit.strings); unit.classes.push(ir::Class { attributes, base, constants, ctx_constants, doc_comment: cls.doc_comment.into(), enum_includes, enum_type, flags: cls.flags, implements, methods: Default::default(), name, properties, requirements, src_loc: ir::SrcLoc::from_span(filename, &cls.span), type_constants, upper_bounds, uses: cls .uses .iter() .map(|use_| ir::ClassId::from_hhbc(*use_, &unit.strings)) .collect(), }); } fn convert_property<'a>( prop: &hhbc::Property<'a>, strings: &ir::StringInterner, ) -> ir::Property<'a> { let attributes = prop .attributes .iter() .map(|a| convert::convert_attribute(a, strings)) .collect_vec(); ir::Property { name: ir::PropId::from_hhbc(prop.name, strings), flags: prop.flags, attributes, visibility: prop.visibility, initial_value: prop .initial_value .as_ref() .map(|tv| convert::convert_typed_value(tv, strings)) .into(), type_info: types::convert_type(&prop.type_info, strings), doc_comment: prop.doc_comment, } } fn convert_ctx_constant<'a>(ctx: &hhbc::CtxConstant<'a>) -> ir::CtxConstant<'a> { ir::CtxConstant { name: ctx.name, recognized: ctx.recognized.iter().cloned().collect(), unrecognized: ctx.unrecognized.iter().cloned().collect(), is_abstract: ctx.is_abstract, } } fn convert_type_constant<'a>( tc: &hhbc::TypeConstant<'a>, strings: &StringInterner, ) -> ir::TypeConstant<'a> { let initializer = tc .initializer .as_ref() .map(|tv| convert::convert_typed_value(tv, strings)) .into(); ir::TypeConstant { name: tc.name, initializer, is_abstract: tc.is_abstract, } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/bc_to_ir/constant.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use hhbc::Constant; use ir::StringInterner; use crate::convert; pub(crate) fn convert_constant<'a>( constant: &Constant<'a>, strings: &StringInterner, ) -> ir::HackConstant { let Constant { name, ref value, attrs, } = *constant; let value = value .as_ref() .map(|tv| convert::convert_typed_value(tv, strings)) .into(); let name = ir::ConstId::from_hhbc(name, strings); ir::HackConstant { name, value, attrs } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/bc_to_ir/context.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::collections::VecDeque; use std::sync::Arc; use ffi::Str; use hash::HashMap; use hhbc::Instruct; use ir::instr; use ir::instr::Special; use ir::BlockId; use ir::BlockIdMap; use ir::FuncBuilder; use ir::Instr; use ir::LocId; use ir::LocalId; use ir::StringInterner; use ir::ValueId; use ir::VarId; use newtype::newtype_int; use crate::convert::UnitState; use crate::sequence::Sequence; pub(crate) type LabelMap<T> = std::collections::HashMap<hhbc::Label, T, newtype::BuildIdHasher<u32>>; // An Addr represents an index into an Instruct Vec. newtype_int!(Addr, u32, AddrMap, AddrIndexSet); impl Addr { pub(crate) const ENTRY: Addr = Addr(0); pub(crate) fn incr(self) -> Addr { Addr::from_usize(self.as_usize() + 1) } /// Can't iterator on Range<T> without implementing `Step for T` which is /// unstable. pub(crate) fn range_to_iter(range: std::ops::Range<Addr>) -> impl Iterator<Item = Addr> { (range.start.0..range.end.0).map(Addr) } } /// Context used during conversion of an HhasBody to an ir::Func. pub(crate) struct Context<'a, 'b> { /// Conversion from hhbc::AdataId to the hhbc:TypedValue it represents. pub(crate) adata_lookup: &'b HashMap<hhbc::AdataId<'a>, Arc<ir::TypedValue>>, /// Source instructions from the bytecode pub(crate) instrs: &'b [Instruct<'a>], pub(crate) addr_to_seq: AddrMap<Sequence>, pub(crate) builder: FuncBuilder<'a>, bid_to_addr: BlockIdMap<Addr>, pub(crate) filename: ir::Filename, pub(crate) label_to_addr: LabelMap<Addr>, pub(crate) loc: ir::LocId, pub(crate) member_op: Option<MemberOpBuilder>, pub(crate) named_local_lookup: Vec<LocalId>, pub(crate) stack: VecDeque<ir::ValueId>, pub(crate) strings: &'b StringInterner, pub(crate) work_queue_pending: VecDeque<Addr>, work_queue_inserted: AddrIndexSet, } impl<'a, 'b> Context<'a, 'b> { pub(crate) fn new( unit: &'b mut ir::Unit<'a>, filename: ir::Filename, func: ir::Func<'a>, instrs: &'b [Instruct<'a>], unit_state: &'b UnitState<'a>, ) -> Self { let mut builder = FuncBuilder::with_func(func, Arc::clone(&unit.strings)); let (label_to_addr, bid_to_addr, addr_to_seq) = Sequence::compute(&mut builder, filename, instrs); let mut ctx = Context { adata_lookup: &unit_state.adata_lookup, instrs, addr_to_seq, label_to_addr, bid_to_addr, builder, filename, loc: ir::LocId::NONE, member_op: None, named_local_lookup: Default::default(), stack: Default::default(), strings: &mut unit.strings, work_queue_pending: Default::default(), work_queue_inserted: Default::default(), }; ctx.add_work_addr(Addr::ENTRY); ctx } pub(crate) fn add_work_addr(&mut self, addr: Addr) { if self.work_queue_inserted.insert(addr) { self.work_queue_pending.push_back(addr); } } pub(crate) fn add_work_bid(&mut self, bid: BlockId) { let addr = self.bid_to_addr[&bid]; self.add_work_addr(addr); } /// Allocate a new Param, register it with the current Block and push it /// onto the stack. pub(crate) fn alloc_and_push_param(&mut self) -> ir::ValueId { let iid = self.builder.alloc_param(); self.push(iid); iid } pub(crate) fn alloc_bid(&mut self) -> BlockId { let bid = self.builder.alloc_bid(); let tcid = self.builder.cur_block().tcid; self.builder.func.block_mut(bid).tcid = tcid; bid } pub(crate) fn debug_get_stack(&self) -> &VecDeque<ir::ValueId> { &self.stack } pub(crate) fn emit(&mut self, i: ir::Instr) -> ir::ValueId { self.builder.emit(i) } pub(crate) fn emit_constant(&mut self, constant: ir::Constant<'a>) -> ir::ValueId { self.builder.emit_constant(constant) } /// Emit an Instr and push its return onto the stack. pub(crate) fn emit_push(&mut self, i: ir::Instr) -> ir::ValueId { let vid = self.emit(i); self.push(vid); vid } /// Emit a Constant and push its return onto the stack. pub(crate) fn emit_push_constant(&mut self, lc: ir::Constant<'a>) -> ir::ValueId { let vid = self.emit_constant(lc); self.push(vid); vid } /// For an Instr that returns multiple values emit_push `count` Select /// instructions. pub(crate) fn emit_selects(&mut self, vid: ValueId, count: u32) { // We need to push the selects onto the stack in reverse order but // we want them to follow the instr in ascending order. let mut selects: Vec<_> = (0..count) .map(|i| self.emit(Instr::Special(Special::Select(vid, i)))) .collect(); selects.reverse(); for instr in selects { self.push(instr); } } pub(crate) fn intern_ffi_str(&mut self, s: Str<'a>) -> ir::UnitBytesId { self.strings.intern_bytes(s.as_ref()) } pub(crate) fn pop(&mut self) -> ir::ValueId { assert!(!self.stack.is_empty()); self.stack.pop_back().unwrap() } pub(crate) fn pop_n(&mut self, n: u32) -> VecDeque<ir::ValueId> { self.stack.split_off(self.stack.len() - n as usize) } pub(crate) fn push(&mut self, vid: ir::ValueId) { self.stack.push_back(vid); } pub(crate) fn push_n(&mut self, values: impl Iterator<Item = ir::ValueId>) { self.stack.extend(values); } /// Save the current stack into VarIds. pub(crate) fn spill_stack(&mut self) -> usize { let sz = self.stack.len(); let stack = std::mem::take(&mut self.stack); for (i, vid) in stack.into_iter().enumerate().rev() { let var = VarId::from_usize(i); self.emit(Instr::set_var(var, vid)); } sz } pub(crate) fn stack_clear(&mut self) { self.stack.clear(); } // Note that idx is relative to the end of the stack! pub(crate) fn stack_get(&mut self, idx: usize) -> ir::ValueId { // Need to treat missing elements like `pop`. assert!(idx < self.stack.len()); self.stack[self.stack.len() - 1 - idx] } pub(crate) fn target_from_label(&mut self, label: hhbc::Label, stack_size: usize) -> BlockId { let addr = *self.label_to_addr.get(&label).unwrap(); self.target_from_addr(addr, stack_size) } pub(crate) fn target_from_addr(&mut self, addr: Addr, stack_size: usize) -> BlockId { let seq = self.addr_to_seq.get_mut(&addr).unwrap(); if let Some(old_size) = seq.input_stack_size.replace(stack_size) { assert_eq!(old_size, stack_size); } let bid = seq.bid; self.add_work_addr(addr); bid } /// Restore the current stack from VarIds. pub(crate) fn unspill_stack(&mut self, n: usize) { for i in 0..n { let var = VarId::from_usize(i); self.emit_push(Instr::get_var(var)); } } } pub(crate) struct MemberOpBuilder { pub(crate) operands: Vec<ValueId>, pub(crate) locals: Vec<LocalId>, pub(crate) base_op: instr::BaseOp, pub(crate) intermediate_ops: Vec<instr::IntermediateOp>, } impl MemberOpBuilder { pub(crate) fn into_member_op(self, final_op: instr::FinalOp) -> instr::MemberOp { instr::MemberOp { final_op, operands: self.operands.into(), locals: self.locals.into(), base_op: self.base_op, intermediate_ops: self.intermediate_ops.into(), } } } pub(crate) fn add_loc( builder: &mut FuncBuilder<'_>, filename: ir::Filename, loc: &hhbc::SrcLoc, ) -> LocId { let loc = ir::func::SrcLoc::from_hhbc(filename, loc); builder.add_loc(loc) }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/bc_to_ir/convert.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::path::Path; use std::sync::Arc; use ffi::Maybe; use hash::HashMap; use hhbc::Fatal; use hhbc::Unit; use ir::StringInterner; /// Convert a hhbc::Unit to an ir::Unit. /// /// Most of the outer structure of the hhbc::Unit maps 1:1 with ir::Unit. As a /// result the "interesting" work is in the conversion of the bytecode to IR /// when converting functions and methods (see `convert_body` in func.rs). /// /// NOTE: hhbc::Unit has to be by-ref because it unfortunately contains a bunch /// of ffi::Slice<T> which cannot own T. /// pub fn bc_to_ir<'a>(unit: &'_ Unit<'a>, filename: &Path) -> ir::Unit<'a> { use std::os::unix::ffi::OsStrExt; let strings = Arc::new(ir::StringInterner::default()); let filename = ir::Filename(strings.intern_bytes(filename.as_os_str().as_bytes())); // Traditionally the HHBC AdataIds are named A_# - but let's not rely on // that. let adata_lookup = unit .adata .iter() .map(|hhbc::Adata { id, value }| (*id, Arc::new(convert_typed_value(value, &strings)))) .collect(); let unit_state = UnitState { adata_lookup }; let constants = unit .constants .as_ref() .iter() .map(|c| crate::constant::convert_constant(c, &strings)) .collect(); let file_attributes: Vec<_> = unit .file_attributes .iter() .map(|a| convert_attribute(a, &strings)) .collect(); let modules: Vec<ir::Module<'a>> = unit .modules .iter() .map(|module| ir::Module { attributes: module .attributes .iter() .map(|a| convert_attribute(a, &strings)) .collect(), name: ir::ClassId::from_hhbc(module.name, &strings), src_loc: ir::SrcLoc::from_span(filename, &module.span), doc_comment: module.doc_comment.into(), }) .collect(); let symbol_refs = convert_symbol_refs(&unit.symbol_refs); let typedefs: Vec<_> = unit .typedefs .iter() .map(|td| crate::types::convert_typedef(td, filename, &strings)) .collect(); let mut ir_unit = ir::Unit { classes: Default::default(), constants, fatal: Default::default(), file_attributes, functions: Default::default(), module_use: unit.module_use.into(), modules, strings, symbol_refs, typedefs, }; // Convert the class containers - but not the methods which are converted // below. This has to be done before the functions. for c in unit.classes.as_ref() { crate::class::convert_class(&mut ir_unit, filename, c); } for f in unit.functions.as_ref() { crate::func::convert_function(&mut ir_unit, filename, f, &unit_state); } // This is where we convert the methods for all the classes. for (idx, c) in unit.classes.as_ref().iter().enumerate() { for m in c.methods.as_ref() { crate::func::convert_method(&mut ir_unit, filename, idx, m, &unit_state); } } if let Maybe::Just(Fatal { op, loc, message }) = unit.fatal { let loc = ir::func::SrcLoc::from_hhbc(filename, &loc); let message = bstr::BString::from(message.as_ref()); ir_unit.fatal = Some(ir::Fatal { op, loc, message }); } ir_unit } pub(crate) struct UnitState<'a> { /// Conversion from hhbc::AdataId to hhbc::TypedValue pub(crate) adata_lookup: HashMap<hhbc::AdataId<'a>, Arc<ir::TypedValue>>, } pub(crate) fn convert_attribute<'a>( attr: &hhbc::Attribute<'a>, strings: &StringInterner, ) -> ir::Attribute { let arguments = attr .arguments .iter() .map(|tv| convert_typed_value(tv, strings)) .collect(); ir::Attribute { name: ir::ClassId::from_hhbc(hhbc::ClassName::new(attr.name), strings), arguments, } } fn convert_symbol_refs<'a>(symbol_refs: &hhbc::SymbolRefs<'a>) -> ir::unit::SymbolRefs<'a> { // TODO: It would be nice if we could determine this stuff from the IR // instead of having to carry it along with the Unit. let classes = symbol_refs.classes.iter().cloned().collect(); let constants = symbol_refs.constants.iter().cloned().collect(); let functions = symbol_refs.functions.iter().cloned().collect(); let includes = symbol_refs.includes.iter().cloned().collect(); ir::unit::SymbolRefs { classes, constants, functions, includes, } } pub(crate) fn convert_typed_value<'a>( tv: &hhbc::TypedValue<'a>, strings: &StringInterner, ) -> ir::TypedValue { match *tv { hhbc::TypedValue::Uninit => ir::TypedValue::Uninit, hhbc::TypedValue::Int(v) => ir::TypedValue::Int(v), hhbc::TypedValue::Bool(v) => ir::TypedValue::Bool(v), hhbc::TypedValue::Float(v) => ir::TypedValue::Float(v), hhbc::TypedValue::String(v) => ir::TypedValue::String(strings.intern_bytes(v.as_ref())), hhbc::TypedValue::LazyClass(v) => { ir::TypedValue::LazyClass(ir::ClassId::from_hhbc(hhbc::ClassName::new(v), strings)) } hhbc::TypedValue::Null => ir::TypedValue::Null, hhbc::TypedValue::Vec(vs) => ir::TypedValue::Vec( vs.iter() .map(|tv| convert_typed_value(tv, strings)) .collect(), ), hhbc::TypedValue::Keyset(vs) => { ir::TypedValue::Keyset(vs.iter().map(|tv| convert_array_key(tv, strings)).collect()) } hhbc::TypedValue::Dict(vs) => ir::TypedValue::Dict( vs.iter() .map(|hhbc::Entry { key, value }| { let key = convert_array_key(key, strings); let value = convert_typed_value(value, strings); (key, value) }) .collect(), ), } } pub(crate) fn convert_array_key<'a>( tv: &hhbc::TypedValue<'a>, strings: &StringInterner, ) -> ir::ArrayKey { match *tv { hhbc::TypedValue::Int(v) => ir::ArrayKey::Int(v), hhbc::TypedValue::LazyClass(v) => { ir::ArrayKey::LazyClass(ir::ClassId::from_hhbc(hhbc::ClassName::new(v), strings)) } hhbc::TypedValue::String(v) => ir::ArrayKey::String(strings.intern_bytes(v.as_ref())), _ => panic!("Unable to convert {tv:?} to ArrayKey"), } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/bc_to_ir/func.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use ffi::Maybe; use hhbc::Body; use hhbc::Function; use hhbc::Method; use hhbc::Param; use ir::func::DefaultValue; use ir::instr::Terminator; use ir::CcReified; use ir::CcThis; use ir::ClassIdMap; use ir::Instr; use ir::LocalId; use log::trace; use newtype::IdVec; use crate::context::Context; use crate::convert; use crate::convert::UnitState; use crate::types; /// Convert a hhbc::Function to an ir::Function pub(crate) fn convert_function<'a>( unit: &mut ir::Unit<'a>, filename: ir::Filename, src: &Function<'a>, unit_state: &UnitState<'a>, ) { trace!("--- convert_function {}", src.name.unsafe_as_str()); let span = ir::SrcLoc::from_span(filename, &src.span); let func = convert_body(unit, filename, &src.body, span, unit_state); ir::verify::verify_func(&func, &Default::default(), &unit.strings); let attributes = src .attributes .as_ref() .iter() .map(|a| convert::convert_attribute(a, &unit.strings)) .collect(); let function = ir::Function { attributes, attrs: src.attrs, coeffects: convert_coeffects(&src.coeffects), func, flags: src.flags, name: ir::FunctionId::from_hhbc(src.name, &unit.strings), }; unit.functions.push(function); } /// Convert a hhbc::Method to an ir::Method pub(crate) fn convert_method<'a>( unit: &mut ir::Unit<'a>, filename: ir::Filename, clsidx: usize, src: &Method<'a>, unit_state: &UnitState<'a>, ) { trace!("--- convert_method {}", src.name.unsafe_as_str()); let span = ir::SrcLoc::from_span(filename, &src.span); let func = convert_body(unit, filename, &src.body, span, unit_state); ir::verify::verify_func(&func, &Default::default(), &unit.strings); let attributes = src .attributes .as_ref() .iter() .map(|attr| crate::convert::convert_attribute(attr, &unit.strings)) .collect(); let method = ir::Method { attributes, attrs: src.attrs, coeffects: convert_coeffects(&src.coeffects), flags: src.flags, func, name: ir::MethodId::from_hhbc(src.name, &unit.strings), visibility: src.visibility, }; unit.classes.get_mut(clsidx).unwrap().methods.push(method); } /// Convert a hhbc::Body to an ir::Func fn convert_body<'a>( unit: &mut ir::Unit<'a>, filename: ir::Filename, body: &Body<'a>, src_loc: ir::SrcLoc, unit_state: &UnitState<'a>, ) -> ir::Func<'a> { let Body { ref body_instrs, ref decl_vars, ref doc_comment, is_memoize_wrapper, is_memoize_wrapper_lsb, num_iters, ref params, ref return_type_info, ref shadowed_tparams, ref upper_bounds, stack_depth: _, } = *body; let tparams: ClassIdMap<_> = upper_bounds .iter() .map(|hhbc::UpperBound { name, bounds }| { let id = unit.strings.intern_bytes(name.as_ref()); let name = ir::ClassId::new(id); let bounds = bounds .iter() .map(|ty| types::convert_type(ty, &unit.strings)) .collect(); (name, ir::TParamBounds { bounds }) }) .collect(); let shadowed_tparams: Vec<ir::ClassId> = shadowed_tparams .iter() .map(|name| { let id = unit.strings.intern_bytes(name.as_ref()); ir::ClassId::new(id) }) .collect(); let mut locs: IdVec<ir::LocId, ir::SrcLoc> = Default::default(); locs.push(src_loc); let func = ir::Func { blocks: Default::default(), doc_comment: doc_comment.clone().into_option(), ex_frames: Default::default(), instrs: Default::default(), is_memoize_wrapper, is_memoize_wrapper_lsb, constants: Default::default(), locs, num_iters, params: Default::default(), return_type: types::convert_maybe_type(return_type_info.as_ref(), &unit.strings), shadowed_tparams, loc_id: ir::LocId::from_usize(0), tparams, }; let mut ctx = Context::new(unit, filename, func, body_instrs, unit_state); for param in params.as_ref() { let ir_param = convert_param(&mut ctx, param); ctx.builder.func.params.push(ir_param); if let ffi::Just(dv) = param.default_value.as_ref() { // This default value will jump to a different start than the // Func::ENTRY_BID. let addr = ctx.label_to_addr[&dv.label]; ctx.add_work_addr(addr); } } for decl in decl_vars.as_ref() { let id = ctx.strings.intern_bytes(decl.as_ref()); ctx.named_local_lookup.push(LocalId::Named(id)); } // Go through the work queue and convert each sequence. We convert a // sequence at a time to ensure that we don't attempt to cross a // try/catch boundary without changing ir::Blocks. while let Some(next) = ctx.work_queue_pending.pop_front() { crate::instrs::convert_sequence(&mut ctx, next); } let cur_bid = ctx.builder.cur_bid(); if !ctx.builder.func.is_terminated(cur_bid) { // This is not a valid input - but might as well do something // reasonable. ctx.emit(Instr::Terminator(Terminator::Unreachable)); } // Mark any empty blocks with 'unreachable'. These will be cleaned up // later but for now need to be valid IR (so they must end with a // terminator). for bid in ctx.builder.func.block_ids() { let block = ctx.builder.func.block_mut(bid); if block.is_empty() { ctx.builder.func.alloc_instr_in(bid, Instr::unreachable()); } } let mut func = ctx.builder.finish(); ir::passes::rpo_sort(&mut func); ir::passes::split_critical_edges(&mut func, true); ir::passes::ssa::run(&mut func, &unit.strings); ir::passes::control::run(&mut func); ir::passes::clean::run(&mut func); trace!( "FUNC:\n{}", ir::print::DisplayFunc::new(&func, true, &unit.strings) ); ir::verify::verify_func(&func, &Default::default(), &unit.strings); func } fn convert_param<'a, 'b>(ctx: &mut Context<'a, 'b>, param: &Param<'a>) -> ir::Param<'a> { let default_value = match &param.default_value { Maybe::Just(dv) => { let init = ctx.target_from_label(dv.label, 0); Some(DefaultValue { init, expr: dv.expr, }) } Maybe::Nothing => None, }; let name = ctx.strings.intern_bytes(param.name.as_ref()); ctx.named_local_lookup.push(LocalId::Named(name)); let user_attributes = param .user_attributes .iter() .map(|a| convert::convert_attribute(a, ctx.strings)) .collect(); ir::Param { default_value, name, is_variadic: param.is_variadic, is_inout: param.is_inout, is_readonly: param.is_readonly, ty: types::convert_maybe_type(param.type_info.as_ref(), ctx.strings), user_attributes, } } fn convert_coeffects<'a>(coeffects: &hhbc::Coeffects<'a>) -> ir::Coeffects<'a> { ir::Coeffects { static_coeffects: coeffects.get_static_coeffects().to_vec(), unenforced_static_coeffects: coeffects.get_unenforced_static_coeffects().to_vec(), fun_param: coeffects.get_fun_param().to_vec(), cc_param: coeffects.get_cc_param().to_vec(), cc_this: coeffects .get_cc_this() .iter() .map(|inner| CcThis { types: inner.types.iter().copied().collect(), }) .collect(), cc_reified: coeffects .get_cc_reified() .iter() .map(|inner| CcReified { is_class: inner.is_class, index: inner.index, types: inner.types.iter().copied().collect(), }) .collect(), closure_parent_scope: coeffects.is_closure_parent_scope(), generator_this: coeffects.generator_this(), caller: coeffects.caller(), } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/bc_to_ir/instrs.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::cmp::Ordering; use std::fmt::Display; use std::sync::Arc; use hhbc::Instruct; use hhbc::Opcode; use hhbc::Pseudo; use ir::instr; use ir::instr::CmpOp; use ir::instr::MemberKey; use ir::instr::Terminator; use ir::print::FmtLocId; use ir::print::FmtRawBid; use ir::print::FmtRawVid; use ir::print::FmtSep; use ir::FCallArgsFlags; use ir::FunctionId; use ir::Instr; use ir::LocalId; use ir::TryCatchId; use ir::UnitBytesId; use ir::ValueId; use log::trace; use crate::context::Addr; use crate::context::Context; use crate::context::MemberOpBuilder; use crate::sequence::SequenceKind; /// Convert the sequence that starts with the offset `addr`. /// /// HHBC is a stack-based VM. We convert a sequence by unspilling the stack (see /// below) and then emulate instruction by instruction. On a change of /// control-flow we spill the stack and then record the target(s) as work to be /// performed. We also record how many entries were on the caller's stack so the /// target knows how many stack slots to expect as input. For instructions which /// have optional control-flow (like a JmpZ) we unspill the stack immediately /// and continue. /// /// Spilling the stack consists of storing the stack slots to temporary VarId /// variables (using Instr::Special(Special::Ssa(Ssa::SetVar))) which are /// named with the stack depth (so the top-of-stack goes to VarId #0, the /// next value on the stack goes to VarId #1, etc). /// /// Unspilling just reverses that process by loading the stack slots (using /// Instr::Special(Special::Ssa(Ssa::GetVar))) with the values of those VarIds. /// /// The SSA pass is responsible for converting the SetVar and GetVar /// instructions into actual SSA form. /// pub(crate) fn convert_sequence<'a, 'b>(ctx: &mut Context<'a, 'b>, addr: Addr) { assert_eq!(ctx.stack.len(), 0); let seq = ctx.addr_to_seq[&addr].clone(); ctx.builder.start_block(seq.bid); ctx.loc = seq.loc_id; trace!( "Sequence {:?}, bid = {}, loc = {}", seq.range, FmtRawBid(seq.bid), FmtLocId(&ctx.builder.func, ctx.loc) ); add_catch_work(ctx, seq.tcid); match seq.kind { SequenceKind::Normal => { // If we never set a input_stack_size then nobody calls this // sequence directly - it must be a root (like the entry block or a // default parameter) and should expect no inputs. ctx.unspill_stack(seq.input_stack_size.unwrap_or(0)); } SequenceKind::Catch => { // Expect a single value. ctx.alloc_and_push_param(); } } for idx in Addr::range_to_iter(seq.range) { let instr = &ctx.instrs[idx.as_usize()]; match instr { Instruct::Opcode(op) => { trace!( " [{idx}] {bid},%{iid} stack: [{stack}] instr {instr:?}, loc {loc:?}", bid = FmtRawBid(ctx.builder.cur_bid()), iid = ctx.builder.func.instrs_len(), stack = FmtSep::comma(ctx.debug_get_stack().iter(), |w, vid| FmtRawVid(*vid) .fmt(w)), loc = ctx.loc ); if !convert_opcode(ctx, op) { // This opcode finishes the sequence. break; } } Instruct::Pseudo(Pseudo::SrcLoc(src_loc)) => { ctx.loc = crate::context::add_loc(&mut ctx.builder, ctx.filename, src_loc); } Instruct::Pseudo( Pseudo::Label(_) | Pseudo::TryCatchBegin | Pseudo::TryCatchMiddle | Pseudo::TryCatchEnd, ) => { // We should never see these - they should be omitted by the // sequence gathering code. unreachable!(); } Instruct::Pseudo( Pseudo::Break | Pseudo::Comment(..) | Pseudo::Continue | Pseudo::TypedValue(..), ) => { // We should never see these in an HHBC sequence outside of the // HackC emitter. unreachable!(); } } } if !ctx.builder.func.is_terminated(ctx.builder.cur_bid()) { trace!(" Non-terminated sequence. Next = {:?}", seq.next); // This sequence ended on a non-terminal. That probably means it falls // into the next sequence. Pretend it just jumps to the next addr. let stack_size = ctx.spill_stack(); if let Some(next) = seq.next { let bid = ctx.target_from_addr(next, stack_size); ctx.emit(Instr::Terminator(Terminator::Jmp(bid, ctx.loc))); } else { ctx.emit(Instr::unreachable()); } } assert_eq!(ctx.stack.len(), 0, "Sequence ended with a non-empty stack!"); } fn convert_base<'a, 'b>(ctx: &mut Context<'a, 'b>, base: &Opcode<'a>) { if let Some(mop) = ctx.member_op.as_ref() { panic!( "Unable to convert base {:?} with existing base {:?}", base, mop.base_op ); } let mut operands: Vec<ValueId> = Vec::new(); let mut locals: Vec<LocalId> = Vec::new(); let loc = ctx.loc; let base_op = match *base { Opcode::BaseC(idx, mode) => { let vid = ctx.stack_get(idx as usize); operands.push(vid); instr::BaseOp::BaseC { mode, loc } } Opcode::BaseGC(idx, mode) => { let vid = ctx.stack_get(idx as usize); operands.push(vid); instr::BaseOp::BaseGC { mode, loc } } Opcode::BaseGL(..) => todo!(), Opcode::BaseSC(idx0, idx1, mode, readonly) => { let vid0 = ctx.stack_get(idx0 as usize); operands.push(vid0); let vid1 = ctx.stack_get(idx1 as usize); operands.push(vid1); instr::BaseOp::BaseSC { mode, readonly, loc, } } Opcode::BaseL(ref local, mode, readonly) => { let lid = convert_local(ctx, local); locals.push(lid); instr::BaseOp::BaseL { mode, readonly, loc, } } Opcode::BaseH => instr::BaseOp::BaseH { loc }, _ => unreachable!(), }; ctx.member_op = Some(MemberOpBuilder { operands, locals, base_op, intermediate_ops: Vec::new(), }); } fn collect_args<'a, 'b>(ctx: &mut Context<'a, 'b>, num_args: u32) -> Vec<ValueId> { let mut res: Vec<ValueId> = (0..num_args).map(|_| ctx.pop()).collect(); res.reverse(); res } fn convert_call<'a, 'b>(ctx: &mut Context<'a, 'b>, call: &Opcode<'a>) { let fcall_args = match call { Opcode::FCallClsMethod(fcall_args, ..) | Opcode::FCallClsMethodD(fcall_args, ..) | Opcode::FCallClsMethodM(fcall_args, ..) | Opcode::FCallClsMethodS(fcall_args, ..) | Opcode::FCallClsMethodSD(fcall_args, ..) | Opcode::FCallCtor(fcall_args, ..) | Opcode::FCallFunc(fcall_args) | Opcode::FCallFuncD(fcall_args, ..) | Opcode::FCallObjMethod(fcall_args, ..) | Opcode::FCallObjMethodD(fcall_args, ..) => fcall_args, _ => unreachable!(), }; let context = ctx.intern_ffi_str(fcall_args.context); let mut num_args = fcall_args.num_args; // These first two stack entries correspond to an HHVM ActRec (in // TypedValue-sized chunks - see kNumActRecCells). The first entry fits // into the ActRec::m_thisUnsafe or ActRec::m_clsUnsafe values (they're a // union). The second entry doesn't matter - it's filled in by the FCall // handler - but HackC always sets it to uninit. // implied obj parameter num_args += 1; // uninit num_args += 1; num_args += fcall_args.flags.contains(FCallArgsFlags::HasUnpack) as u32; num_args += fcall_args.flags.contains(FCallArgsFlags::HasGenerics) as u32; use instr::CallDetail; let detail = match *call { Opcode::FCallClsMethod(_, _, log) => { num_args += 2; CallDetail::FCallClsMethod { log } } Opcode::FCallClsMethodD(_, class, method) => { let clsid = ir::ClassId::from_hhbc(class, ctx.strings); let method = ir::MethodId::from_hhbc(method, ctx.strings); CallDetail::FCallClsMethodD { clsid, method } } Opcode::FCallClsMethodM(_, _, log, method) => { num_args += 1; let method = ir::MethodId::from_hhbc(method, ctx.strings); CallDetail::FCallClsMethodM { method, log } } Opcode::FCallClsMethodS(_, _, clsref) => { num_args += 1; CallDetail::FCallClsMethodS { clsref } } Opcode::FCallClsMethodSD(_, _, clsref, method) => { let method = ir::MethodId::from_hhbc(method, ctx.strings); CallDetail::FCallClsMethodSD { clsref, method } } Opcode::FCallCtor(_, _) => CallDetail::FCallCtor, Opcode::FCallFunc(_) => { num_args += 1; CallDetail::FCallFunc } Opcode::FCallFuncD(_, func) => { let func = FunctionId::from_hhbc(func, ctx.strings); CallDetail::FCallFuncD { func } } Opcode::FCallObjMethod(_, _, flavor) => { num_args += 1; CallDetail::FCallObjMethod { flavor } } Opcode::FCallObjMethodD(_, _, flavor, method) => { let method = ir::MethodId::from_hhbc(method, ctx.strings); CallDetail::FCallObjMethodD { flavor, method } } _ => unreachable!(), }; let mut operands = collect_args(ctx, num_args); match *call { Opcode::FCallClsMethod(..) | Opcode::FCallClsMethodD(..) | Opcode::FCallClsMethodM(..) | Opcode::FCallClsMethodS(..) | Opcode::FCallClsMethodSD(..) | Opcode::FCallFunc(..) | Opcode::FCallFuncD(..) => { // Remove the two required uninit values. operands.splice(0..2, []); // We'd like to check that the removed items were actually uninit - // but because our stack could be coming from an unspill they could // be hidden behind block params. } Opcode::FCallCtor(..) | Opcode::FCallObjMethod(..) | Opcode::FCallObjMethodD(..) => { // Remove the required uninit value. operands.splice(1..2, []); } _ => unreachable!(), }; // inout return slots let inouts: Option<Box<[u32]>> = { let mut buf: Vec<u32> = Vec::new(); for (idx, &inout) in fcall_args.inouts.as_ref().iter().enumerate() { if inout { buf.push(idx as u32); ctx.pop(); } } if buf.is_empty() { None } else { Some(buf.into()) } }; let readonly = { let mut buf: Vec<u32> = Vec::new(); for (idx, &readonly) in fcall_args.readonly.as_ref().iter().enumerate() { if readonly { buf.push(idx as u32); } } if buf.is_empty() { None } else { Some(buf.into()) } }; let call = instr::Call { context, detail, flags: fcall_args.flags, inouts, loc: ctx.loc, num_rets: fcall_args.num_rets, operands: operands.into(), readonly, }; let num_rets = call.num_rets; if fcall_args.has_async_eager_target() { let async_bid = ctx.alloc_bid(); let eager_bid = ctx.alloc_bid(); let stack_size = ctx.spill_stack(); ctx.emit(Instr::Terminator(Terminator::CallAsync( Box::new(call), [async_bid, eager_bid], ))); // The eager side is tricky - we need a param to receive the produced // value - but then we need to spill the args and call our target. ctx.builder.start_block(eager_bid); ctx.unspill_stack(stack_size); ctx.alloc_and_push_param(); let stack_size2 = ctx.spill_stack(); let eager_bid2 = ctx.target_from_label(fcall_args.async_eager_target, stack_size2); ctx.emit(Instr::jmp(eager_bid2, ctx.loc)); ctx.builder.start_block(async_bid); ctx.unspill_stack(stack_size); ctx.alloc_and_push_param(); // And continue with the async (non-eager) block. } else { let vid = ctx.emit(Instr::call(call)); match num_rets { 0 => {} 1 => ctx.push(vid), _ => ctx.emit_selects(vid, num_rets), } } } fn convert_dim<'a, 'b>(ctx: &mut Context<'a, 'b>, opcode: &Opcode<'a>) { if ctx.member_op.as_mut().is_none() { panic!("Unable to convert dim {:?} without existing base", opcode); }; match *opcode { Opcode::Dim(mode, key) => { let (key, readonly, value, local) = convert_member_key(ctx, &key); let member_op = ctx.member_op.as_mut().unwrap(); if let Some(value) = value { member_op.operands.push(value); } if let Some(local) = local { member_op.locals.push(local); } member_op.intermediate_ops.push(instr::IntermediateOp { mode, key, readonly, loc: ctx.loc, }); } _ => unreachable!(), } } fn member_op_mutates_stack_base(op: &instr::MemberOp) -> bool { use instr::BaseOp; use instr::FinalOp; let write_op = match op.final_op { FinalOp::QueryM { .. } => false, FinalOp::SetRangeM { .. } | FinalOp::UnsetM { .. } | FinalOp::IncDecM { .. } | FinalOp::SetM { .. } | FinalOp::SetOpM { .. } => true, }; let base_key_is_element_access = op.intermediate_ops.get(0).map_or_else( || op.final_op.key().map_or(true, |k| k.is_element_access()), |dim| dim.key.is_element_access(), ); match op.base_op { BaseOp::BaseC { .. } => base_key_is_element_access && write_op, BaseOp::BaseGC { .. } | BaseOp::BaseH { .. } | BaseOp::BaseL { .. } | BaseOp::BaseSC { .. } | BaseOp::BaseST { .. } => false, } } fn member_key_stack_count(k: &MemberKey) -> usize { match k { MemberKey::EC | MemberKey::PC => 1, MemberKey::EI(_) | MemberKey::EL | MemberKey::ET(_) | MemberKey::PL | MemberKey::PT(_) | MemberKey::QT(_) | MemberKey::W => 0, } } fn convert_member_key<'a, 'b>( ctx: &mut Context<'a, 'b>, key: &hhbc::MemberKey<'a>, ) -> ( instr::MemberKey, ir::ReadonlyOp, Option<ValueId>, Option<LocalId>, ) { match *key { hhbc::MemberKey::EC(idx, readonly) => { let vid = ctx.stack_get(idx as usize); (instr::MemberKey::EC, readonly, Some(vid), None) } hhbc::MemberKey::EI(i, readonly) => (instr::MemberKey::EI(i), readonly, None, None), hhbc::MemberKey::EL(local, readonly) => { let lid = convert_local(ctx, &local); (instr::MemberKey::EL, readonly, None, Some(lid)) } hhbc::MemberKey::ET(s, readonly) => { let id = ctx.intern_ffi_str(s); (instr::MemberKey::ET(id), readonly, None, None) } hhbc::MemberKey::PC(idx, readonly) => { let vid = ctx.stack_get(idx as usize); (instr::MemberKey::PC, readonly, Some(vid), None) } hhbc::MemberKey::PL(local, readonly) => { let lid = convert_local(ctx, &local); (instr::MemberKey::PL, readonly, None, Some(lid)) } hhbc::MemberKey::PT(s, readonly) => { let id = ir::PropId::from_hhbc(s, ctx.strings); (instr::MemberKey::PT(id), readonly, None, None) } hhbc::MemberKey::QT(s, readonly) => { let id = ir::PropId::from_hhbc(s, ctx.strings); (instr::MemberKey::QT(id), readonly, None, None) } hhbc::MemberKey::W => (instr::MemberKey::W, ir::ReadonlyOp::Any, None, None), } } fn convert_final<'a, 'b>(ctx: &mut Context<'a, 'b>, fin: &Opcode<'a>) { let mut member_op = if let Some(mop) = ctx.member_op.take() { mop } else { panic!("Unable to convert final {:?} without existing base", fin); }; let loc = ctx.loc; let (member_op, pop_count, pushes_value) = match *fin { Opcode::IncDecM(num, inc_dec_op, key) => { let (key, readonly, value, local) = convert_member_key(ctx, &key); if let Some(value) = value { member_op.operands.push(value); } if let Some(local) = local { member_op.locals.push(local); } let mop = member_op.into_member_op(instr::FinalOp::IncDecM { key, readonly, inc_dec_op, loc, }); (mop, num, true) } Opcode::QueryM(num, query_m_op, key) => { let (key, readonly, value, local) = convert_member_key(ctx, &key); if let Some(value) = value { member_op.operands.push(value); } if let Some(local) = local { member_op.locals.push(local); } let mop = member_op.into_member_op(instr::FinalOp::QueryM { key, readonly, query_m_op, loc, }); (mop, num, true) } Opcode::SetM(num, key) => { let (key, readonly, value, local) = convert_member_key(ctx, &key); if let Some(value) = value { member_op.operands.push(value); } if let Some(local) = local { member_op.locals.push(local); } member_op.operands.push(ctx.pop()); let mop = member_op.into_member_op(instr::FinalOp::SetM { key, readonly, loc }); (mop, num, true) } Opcode::SetOpM(num, set_op_op, key) => { let (key, readonly, value, local) = convert_member_key(ctx, &key); if let Some(value) = value { member_op.operands.push(value); } if let Some(local) = local { member_op.locals.push(local); } member_op.operands.push(ctx.pop()); let mop = member_op.into_member_op(instr::FinalOp::SetOpM { key, readonly, set_op_op, loc, }); (mop, num, true) } Opcode::SetRangeM(num, sz, set_range_op) => { let s1 = ctx.pop(); let s2 = ctx.pop(); let s3 = ctx.pop(); member_op.operands.push(s3); member_op.operands.push(s2); member_op.operands.push(s1); let mop = member_op.into_member_op(instr::FinalOp::SetRangeM { sz, set_range_op, loc, }); (mop, num, false) } Opcode::UnsetM(num, key) => { let (key, readonly, value, local) = convert_member_key(ctx, &key); if let Some(value) = value { member_op.operands.push(value); } if let Some(local) = local { member_op.locals.push(local); } let mop = member_op.into_member_op(instr::FinalOp::UnsetM { key, readonly, loc }); (mop, num, false) } _ => unreachable!(), }; let expected_stack = { let mut count = match member_op.base_op { instr::BaseOp::BaseC { .. } => 1, instr::BaseOp::BaseGC { .. } => 1, instr::BaseOp::BaseH { .. } => 0, instr::BaseOp::BaseL { .. } => 0, instr::BaseOp::BaseSC { .. } => 2, instr::BaseOp::BaseST { .. } => 1, }; for op in member_op.intermediate_ops.iter() { count += member_key_stack_count(&op.key); } if let Some(key) = member_op.final_op.key() { count += member_key_stack_count(key); } count }; let mut expected_stack = ctx.pop_n(expected_stack as u32); let num_rets = member_op.num_values(); let mutates_stack_base = member_op_mutates_stack_base(&member_op); let mut vid = ctx.emit(instr::Instr::MemberOp(member_op)); match (num_rets, mutates_stack_base) { (0, false) | (1, false) => {} (1, true) => { // The base instruction mutates its stack entry but doesn't return // any value: // BaseC // UnsetM expected_stack[0] = vid; } (2, true) => { // The base instruction mutates its stack entry and also returns a // value: // BaseC // SetM let ret0 = ctx.emit(Instr::Special(instr::Special::Select(vid, 0))); let ret1 = ctx.emit(Instr::Special(instr::Special::Select(vid, 1))); expected_stack[0] = ret1; vid = ret0; } // (0, true) => mutates its stack but no returns? // (2, false) => multiple returns but doesn't mutate the stack? _ => panic!("Unexpected combination ({num_rets}, {mutates_stack_base})"), } let pop_count = pop_count as usize; match pop_count.cmp(&expected_stack.len()) { Ordering::Greater => { ctx.pop_n((pop_count - expected_stack.len()) as u32); } Ordering::Less => { expected_stack.shrink_to(expected_stack.len() - pop_count); ctx.push_n(expected_stack.into_iter()); } Ordering::Equal => { // Already popped the right amount. } } if pushes_value { ctx.push(vid); } } fn convert_include<'a, 'b>(ctx: &mut Context<'a, 'b>, ie: &Opcode<'a>) { use instr::IncludeKind; let kind = match ie { Opcode::Eval => IncludeKind::Eval, Opcode::Incl => IncludeKind::Include, Opcode::InclOnce => IncludeKind::IncludeOnce, Opcode::Req => IncludeKind::Require, Opcode::ReqDoc => IncludeKind::RequireOnceDoc, Opcode::ReqOnce => IncludeKind::RequireOnce, _ => unreachable!(), }; let vid = ctx.pop(); let loc = ctx.loc; let ie = instr::IncludeEval { kind, vid, loc }; ctx.emit_push(Instr::Hhbc(instr::Hhbc::IncludeEval(ie))); } fn convert_local<'a, 'b>(ctx: &mut Context<'a, 'b>, local: &hhbc::Local) -> LocalId { if let Some(local) = ctx.named_local_lookup.get(local.as_usize()) { *local } else { // Convert the hhbc::Local ID to a 0-based number. let id = ir::UnnamedLocalId::from_usize(local.as_usize() - ctx.named_local_lookup.len()); LocalId::Unnamed(id) } } fn convert_local_range<'a, 'b>( ctx: &mut Context<'a, 'b>, range: &hhbc::LocalRange, ) -> Box<[LocalId]> { let mut locals = Vec::default(); if range.start != hhbc::Local::INVALID && range.len != 0 { let size = range.len as usize; for idx in 0..size { let local = hhbc::Local::from_usize(range.start.as_usize() + idx); let lid = convert_local(ctx, &local); locals.push(lid); } } locals.into() } fn convert_iterator<'a, 'b>(ctx: &mut Context<'a, 'b>, opcode: &Opcode<'a>) { match *opcode { Opcode::IterInit(ref args, label) => { let hhbc::IterArgs { iter_id, ref key_id, ref val_id, } = *args; let key_lid = key_id.is_valid().then(|| convert_local(ctx, key_id)); let value_lid = convert_local(ctx, val_id); let base_iid = ctx.pop(); let stack_size = ctx.spill_stack(); let next_bid = ctx.builder.alloc_bid(); let done_bid = ctx.target_from_label(label, stack_size); let args = instr::IteratorArgs::new(iter_id, key_lid, value_lid, done_bid, next_bid, ctx.loc); ctx.emit(Instr::Terminator(Terminator::IterInit(args, base_iid))); ctx.builder.start_block(next_bid); ctx.unspill_stack(stack_size); } Opcode::IterNext(ref args, label) => { let hhbc::IterArgs { iter_id, ref key_id, ref val_id, } = *args; let key_lid = key_id.is_valid().then(|| convert_local(ctx, key_id)); let value_lid = convert_local(ctx, val_id); let stack_size = ctx.spill_stack(); let next_bid = ctx.builder.alloc_bid(); let done_bid = ctx.target_from_label(label, stack_size); let args = instr::IteratorArgs::new(iter_id, key_lid, value_lid, done_bid, next_bid, ctx.loc); ctx.emit(Instr::Terminator(Terminator::IterNext(args))); ctx.builder.start_block(next_bid); ctx.unspill_stack(stack_size); } _ => unreachable!(), } } fn convert_control_flow<'a, 'b>(ctx: &mut Context<'a, 'b>, opcode: &Opcode<'a>) { let loc = ctx.loc; match *opcode { Opcode::JmpNZ(label) | Opcode::JmpZ(label) => { let s1 = ctx.pop(); let stack_size = ctx.spill_stack(); let true_bid = ctx.target_from_label(label, stack_size); let false_bid = ctx.alloc_bid(); let pred = match *opcode { Opcode::JmpNZ(_) => ir::Predicate::NonZero, Opcode::JmpZ(_) => ir::Predicate::Zero, _ => unreachable!(), }; let instr = Terminator::JmpOp { cond: s1, pred, targets: [true_bid, false_bid], loc, }; ctx.emit(Instr::Terminator(instr)); ctx.builder.start_block(false_bid); ctx.unspill_stack(stack_size); } Opcode::Switch(bounded, base, ref targets) => { let s1 = ctx.pop(); let stack_size = ctx.spill_stack(); let targets = targets .iter() .map(|label| ctx.target_from_label(*label, stack_size)) .collect(); let instr = Terminator::Switch { cond: s1, bounded, base, targets, loc, }; ctx.emit(Instr::Terminator(instr)); } Opcode::SSwitch { ref cases, ref targets, _0: _, } => { let s1 = ctx.pop(); let stack_size = ctx.spill_stack(); let cases = cases.iter().map(|case| ctx.intern_ffi_str(*case)).collect(); let targets = targets .iter() .map(|label| ctx.target_from_label(*label, stack_size)) .collect(); let instr = Terminator::SSwitch { cond: s1, cases, targets, loc, }; ctx.emit(Instr::Terminator(instr)); } _ => unreachable!(), } } #[b2i_macros::bc_to_ir] fn convert_opcode<'a, 'b>(ctx: &mut Context<'a, 'b>, opcode: &Opcode<'a>) -> bool { use instr::Hhbc; use ir::Constant; let loc = ctx.loc; enum Action<'a> { Emit(Instr), Constant(Constant<'a>), None, Push(Instr), Terminal(Terminator), } // (Normally Rust doesn't let you have an attribute on a statement. This // only works because the outer function is also wrapped with #[bc_to_ir] // and it looks for this.) // // The embedded macros in this match expression (simple!, todo!) use the // hhbc opcode table to figure out how to convert standard opcodes. #[bc_to_ir] let action = match *opcode { Opcode::BaseC(..) | Opcode::BaseGC(..) | Opcode::BaseGL(..) | Opcode::BaseSC(..) | Opcode::BaseL(..) | Opcode::BaseH => { convert_base(ctx, opcode); Action::None } Opcode::Dim(..) => { convert_dim(ctx, opcode); Action::None } Opcode::QueryM(..) | Opcode::SetM(..) | Opcode::IncDecM(..) | Opcode::SetOpM(..) | Opcode::UnsetM(..) | Opcode::SetRangeM(..) => { convert_final(ctx, opcode); Action::None } Opcode::FCallClsMethod { .. } | Opcode::FCallClsMethodD { .. } | Opcode::FCallClsMethodM { .. } | Opcode::FCallClsMethodS { .. } | Opcode::FCallClsMethodSD { .. } | Opcode::FCallCtor(..) | Opcode::FCallFunc(..) | Opcode::FCallFuncD { .. } | Opcode::FCallObjMethod { .. } | Opcode::FCallObjMethodD { .. } => { convert_call(ctx, opcode); Action::None } Opcode::Eval | Opcode::Incl | Opcode::InclOnce | Opcode::Req | Opcode::ReqDoc | Opcode::ReqOnce => { convert_include(ctx, opcode); Action::None } Opcode::IterInit(_, _) | Opcode::IterNext(_, _) => { convert_iterator(ctx, opcode); Action::None } Opcode::Jmp(label) => { let stack_size = ctx.spill_stack(); let bid = ctx.target_from_label(label, stack_size); Action::Terminal(Terminator::Jmp(bid, ctx.loc)) } Opcode::Enter(label) => { let stack_size = ctx.spill_stack(); let bid = ctx.target_from_label(label, stack_size); Action::Terminal(Terminator::Enter(bid, ctx.loc)) } Opcode::JmpNZ(..) | Opcode::JmpZ(..) | Opcode::Switch(..) | Opcode::SSwitch { .. } => { convert_control_flow(ctx, opcode); Action::None } // MemoGet is a terminal - but it needs to use 'push_expected_param' // after the push so it can't use convert_terminal(). Opcode::MemoGet(else_label, ref locals) => { let stack_size = ctx.spill_stack(); let value_bid = ctx.builder.alloc_bid(); let else_bid = ctx.target_from_label(else_label, stack_size); let locals = convert_local_range(ctx, locals); let get = instr::MemoGet::new(value_bid, else_bid, &locals, loc); ctx.emit(Instr::Terminator(Terminator::MemoGet(get))); ctx.builder.start_block(value_bid); ctx.unspill_stack(stack_size); ctx.alloc_and_push_param(); Action::None } Opcode::MemoGetEager([no_value_label, suspended_label], _, ref locals) => { let stack_size = ctx.spill_stack(); let eager_bid = ctx.builder.alloc_bid(); let no_value_bid = ctx.target_from_label(no_value_label, stack_size); let suspended_bid = ctx.alloc_bid(); let locals = convert_local_range(ctx, locals); let get = instr::MemoGetEager::new(no_value_bid, suspended_bid, eager_bid, &locals, loc); ctx.emit(Instr::Terminator(Terminator::MemoGetEager(get))); ctx.builder.start_block(suspended_bid); ctx.unspill_stack(stack_size); ctx.alloc_and_push_param(); let stack_size2 = ctx.spill_stack(); let suspended_bid2 = ctx.target_from_label(suspended_label, stack_size2); ctx.emit(Instr::jmp(suspended_bid2, ctx.loc)); ctx.builder.start_block(eager_bid); ctx.unspill_stack(stack_size); ctx.alloc_and_push_param(); Action::None } Opcode::Fatal(subop1) => { let s1 = ctx.pop(); // Fatal throws away the rest of the stack. ctx.stack_clear(); Action::Terminal(Terminator::Fatal(s1, subop1, ctx.loc)) } Opcode::ThrowAsTypeStructException => { let s2 = ctx.pop(); let s1 = ctx.pop(); ctx.stack_clear(); Action::Terminal(Terminator::ThrowAsTypeStructException([s1, s2], ctx.loc)) } Opcode::Dict(name) => { let tv = Arc::clone(&ctx.adata_lookup[&name]); debug_assert!(matches!(*tv, ir::TypedValue::Dict(_))); Action::Constant(Constant::Array(tv)) } Opcode::Keyset(name) => { let tv = Arc::clone(&ctx.adata_lookup[&name]); debug_assert!(matches!(*tv, ir::TypedValue::Keyset(_))); Action::Constant(Constant::Array(tv)) } Opcode::Vec(name) => { let tv = Arc::clone(&ctx.adata_lookup[&name]); debug_assert!(matches!(*tv, ir::TypedValue::Vec(_))); Action::Constant(Constant::Array(tv)) } Opcode::AKExists => simple!(Hhbc::AKExists), Opcode::Add => simple!(Hhbc::Add), Opcode::AddElemC => simple!(Hhbc::AddElemC), Opcode::AddNewElemC => simple!(Hhbc::AddNewElemC), Opcode::ArrayIdx => simple!(Hhbc::ArrayIdx), Opcode::ArrayMarkLegacy => simple!(Hhbc::ArrayMarkLegacy), Opcode::ArrayUnmarkLegacy => simple!(Hhbc::ArrayUnmarkLegacy), Opcode::AssertRATL => todo!(), Opcode::AssertRATStk => todo!(), Opcode::Await => simple!(Hhbc::Await), Opcode::AwaitAll => simple!(Hhbc::AwaitAll), Opcode::BareThis => simple!(Hhbc::BareThis), Opcode::BitAnd => simple!(Hhbc::BitAnd), Opcode::BitNot => simple!(Hhbc::BitNot), Opcode::BitOr => simple!(Hhbc::BitOr), Opcode::BitXor => simple!(Hhbc::BitXor), Opcode::BreakTraceHint => todo!(), Opcode::CGetCUNop => todo!(), Opcode::CGetG => simple!(Hhbc::CGetG), Opcode::CGetL => simple!(Hhbc::CGetL), Opcode::CGetQuietL => simple!(Hhbc::CGetQuietL), Opcode::CGetS => simple!(Hhbc::CGetS), Opcode::CUGetL => simple!(Hhbc::CUGetL), Opcode::CastBool => simple!(Hhbc::CastBool), Opcode::CastDict => simple!(Hhbc::CastDict), Opcode::CastDouble => simple!(Hhbc::CastDouble), Opcode::CastInt => simple!(Hhbc::CastInt), Opcode::CastKeyset => simple!(Hhbc::CastKeyset), Opcode::CastString => simple!(Hhbc::CastString), Opcode::CastVec => simple!(Hhbc::CastVec), Opcode::ChainFaults => simple!(Hhbc::ChainFaults), Opcode::CheckProp => simple!(Hhbc::CheckProp), Opcode::CheckClsReifiedGenericMismatch => simple!(Hhbc::CheckClsReifiedGenericMismatch), Opcode::CheckClsRGSoft => simple!(Hhbc::CheckClsRGSoft), Opcode::CheckThis => simple!(Hhbc::CheckThis), Opcode::ClassGetC => simple!(Hhbc::ClassGetC), Opcode::ClassHasReifiedGenerics => simple!(Hhbc::ClassHasReifiedGenerics), Opcode::ClassName => simple!(Hhbc::ClassName), Opcode::Clone => simple!(Hhbc::Clone), Opcode::ClsCns => simple!(Hhbc::ClsCns), Opcode::ClsCnsD => simple!(Hhbc::ClsCnsD), Opcode::ClsCnsL => simple!(Hhbc::ClsCnsL), Opcode::Cmp => simple!(Hhbc::Cmp), Opcode::ColFromArray => simple!(Hhbc::ColFromArray), Opcode::CombineAndResolveTypeStruct => simple!(Hhbc::CombineAndResolveTypeStruct), Opcode::Concat => simple!(Hhbc::Concat), Opcode::ConcatN => simple!(Hhbc::ConcatN), Opcode::ContCheck => simple!(Hhbc::ContCheck), Opcode::ContCurrent => simple!(Hhbc::ContCurrent), Opcode::ContEnter => simple!(Hhbc::ContEnter), Opcode::ContGetReturn => simple!(Hhbc::ContGetReturn), Opcode::ContKey => simple!(Hhbc::ContKey), Opcode::ContRaise => simple!(Hhbc::ContRaise), Opcode::ContValid => simple!(Hhbc::ContValid), Opcode::CreateCont => simple!(Hhbc::CreateCont), Opcode::CreateSpecialImplicitContext => simple!(Hhbc::CreateSpecialImplicitContext), Opcode::DblAsBits => todo!(), Opcode::Dir => simple!(Constant::Dir), Opcode::Div => simple!(Hhbc::Div), Opcode::Double => simple!(Constant::Float), Opcode::Eq => simple!(Hhbc::CmpOp, CmpOp::Eq), Opcode::Exit => simple!(Terminator::Exit), Opcode::False => simple!(Constant::Bool, false), Opcode::File => simple!(Constant::File), Opcode::FuncCred => simple!(Constant::FuncCred), Opcode::GetClsRGProp => simple!(Hhbc::GetClsRGProp), Opcode::GetMemoKeyL => simple!(Hhbc::GetMemoKeyL), Opcode::Gt => simple!(Hhbc::CmpOp, CmpOp::Gt), Opcode::Gte => simple!(Hhbc::CmpOp, CmpOp::Gte), Opcode::HasReifiedParent => simple!(Hhbc::HasReifiedParent), Opcode::Idx => simple!(Hhbc::Idx), Opcode::IncDecG => todo!(), Opcode::IncDecL => simple!(Hhbc::IncDecL), Opcode::IncDecS => simple!(Hhbc::IncDecS), Opcode::InitProp => simple!(Hhbc::InitProp), Opcode::InstanceOf => todo!(), Opcode::InstanceOfD => simple!(Hhbc::InstanceOfD), Opcode::Int => simple!(Constant::Int), Opcode::IsLateBoundCls => simple!(Hhbc::IsLateBoundCls), Opcode::IsTypeC => simple!(Hhbc::IsTypeC), Opcode::IsTypeL => simple!(Hhbc::IsTypeL), Opcode::IsTypeStructC => simple!(Hhbc::IsTypeStructC), Opcode::IsUnsetL => todo!(), Opcode::IssetG => simple!(Hhbc::IssetG), Opcode::IssetL => simple!(Hhbc::IssetL), Opcode::IssetS => simple!(Hhbc::IssetS), Opcode::IterFree => simple!(Hhbc::IterFree), Opcode::LIterFree => todo!(), Opcode::LIterInit => todo!(), Opcode::LIterNext => todo!(), Opcode::LateBoundCls => simple!(Hhbc::LateBoundCls), Opcode::LazyClass => simple!(Hhbc::LazyClass), Opcode::LazyClassFromClass => simple!(Hhbc::LazyClassFromClass), Opcode::LockObj => simple!(Hhbc::LockObj), Opcode::Lt => simple!(Hhbc::CmpOp, CmpOp::Lt), Opcode::Lte => simple!(Hhbc::CmpOp, CmpOp::Lte), Opcode::MemoSet => simple!(Hhbc::MemoSet), Opcode::MemoSetEager => simple!(Hhbc::MemoSetEager), Opcode::Method => simple!(Constant::Method), Opcode::Mod => simple!(Hhbc::Modulo), Opcode::Mul => simple!(Hhbc::Mul), Opcode::NSame => simple!(Hhbc::CmpOp, CmpOp::NSame), Opcode::NativeImpl => simple!(Terminator::NativeImpl), Opcode::Neq => simple!(Hhbc::CmpOp, CmpOp::Neq), Opcode::NewCol => simple!(Constant::NewCol), Opcode::NewDictArray => simple!(Hhbc::NewDictArray), Opcode::NewKeysetArray => simple!(Hhbc::NewKeysetArray), Opcode::NewObj => simple!(Hhbc::NewObj), Opcode::NewObjD => simple!(Hhbc::NewObjD), Opcode::NewObjS => simple!(Hhbc::NewObjS), Opcode::NewPair => simple!(Hhbc::NewPair), Opcode::NewVec => simple!(Hhbc::NewVec), Opcode::Nop => todo!(), Opcode::Not => simple!(Hhbc::Not), Opcode::Null => simple!(Constant::Null), Opcode::NullUninit => simple!(Constant::Uninit), Opcode::OODeclExists => simple!(Hhbc::OODeclExists), Opcode::ParentCls => simple!(Hhbc::ParentCls), Opcode::PopL => simple!(Hhbc::SetL), Opcode::PopU => todo!(), Opcode::PopU2 => todo!(), Opcode::Pow => simple!(Hhbc::Pow), Opcode::Print => simple!(Hhbc::Print), Opcode::PushL => simple!(Hhbc::ConsumeL), #[rustfmt::skip] Opcode::RaiseClassStringConversionWarning => simple!(Hhbc::RaiseClassStringConversionWarning), Opcode::RecordReifiedGeneric => simple!(Hhbc::RecordReifiedGeneric), Opcode::ResolveClass => simple!(Hhbc::ResolveClass), Opcode::ResolveClsMethod => simple!(Hhbc::ResolveClsMethod), Opcode::ResolveClsMethodD => simple!(Hhbc::ResolveClsMethodD), Opcode::ResolveClsMethodS => simple!(Hhbc::ResolveClsMethodS), Opcode::ResolveFunc => simple!(Hhbc::ResolveFunc), Opcode::ResolveMethCaller => simple!(Hhbc::ResolveMethCaller), Opcode::ResolveRClsMethod => simple!(Hhbc::ResolveRClsMethod), Opcode::ResolveRClsMethodD => simple!(Hhbc::ResolveRClsMethodD), Opcode::ResolveRClsMethodS => simple!(Hhbc::ResolveRClsMethodS), Opcode::ResolveRFunc => simple!(Hhbc::ResolveRFunc), Opcode::RetC => simple!(Terminator::Ret), Opcode::RetCSuspended => simple!(Terminator::RetCSuspended), Opcode::RetM => simple!(Terminator::RetM), Opcode::Same => simple!(Hhbc::CmpOp, CmpOp::Same), Opcode::Select => todo!(), Opcode::SelfCls => simple!(Hhbc::SelfCls), Opcode::SetG => simple!(Hhbc::SetG), Opcode::SetL => simple!(Hhbc::SetL), Opcode::SetImplicitContextByValue => simple!(Hhbc::SetImplicitContextByValue), Opcode::SetOpG => simple!(Hhbc::SetOpG), Opcode::SetOpL => simple!(Hhbc::SetOpL), Opcode::SetOpS => simple!(Hhbc::SetOpS), Opcode::SetS => simple!(Hhbc::SetS), Opcode::Shl => simple!(Hhbc::Shl), Opcode::Shr => simple!(Hhbc::Shr), Opcode::Silence => simple!(Hhbc::Silence), Opcode::Sub => simple!(Hhbc::Sub), Opcode::This => simple!(Hhbc::This), Opcode::Throw => simple!(Terminator::Throw), Opcode::ThrowNonExhaustiveSwitch => simple!(Hhbc::ThrowNonExhaustiveSwitch), Opcode::True => simple!(Constant::Bool, true), Opcode::UGetCUNop => todo!(), Opcode::UnsetG => simple!(Hhbc::UnsetG), Opcode::UnsetL => simple!(Hhbc::UnsetL), Opcode::VerifyImplicitContextState => simple!(Hhbc::VerifyImplicitContextState), Opcode::VerifyOutType => simple!(Hhbc::VerifyOutType), Opcode::VerifyParamType => simple!(Hhbc::VerifyParamType), Opcode::VerifyParamTypeTS => simple!(Hhbc::VerifyParamTypeTS), Opcode::VerifyRetNonNullC => todo!(), Opcode::VerifyRetTypeC => simple!(Hhbc::VerifyRetTypeC), Opcode::VerifyRetTypeTS => simple!(Hhbc::VerifyRetTypeTS), Opcode::WHResult => simple!(Hhbc::WHResult), Opcode::Yield => simple!(Hhbc::Yield), Opcode::YieldK => simple!(Hhbc::YieldK), Opcode::ClassGetTS => { let s1 = ctx.pop(); let vid = ctx.emit(Instr::Hhbc(Hhbc::ClassGetTS(s1, ctx.loc))); ctx.emit_selects(vid, 2); Action::None } Opcode::CGetL2(ref local) => { let lid = convert_local(ctx, local); let s1 = ctx.pop(); ctx.emit_push(Instr::Hhbc(Hhbc::CGetL(lid, loc))); ctx.push(s1); Action::None } Opcode::CnsE(id) => Action::Constant(Constant::Named(id)), Opcode::CreateCl(num_args, class) => { let operands = collect_args(ctx, num_args); let clsid = ir::ClassId::from_hhbc(class, ctx.strings); Action::Push(Instr::Hhbc(Hhbc::CreateCl { operands: operands.into(), clsid, loc, })) } Opcode::Dup => { let s1 = ctx.pop(); ctx.push(s1); ctx.push(s1); Action::None } Opcode::NewStructDict(keys) => { let keys: Box<[UnitBytesId]> = keys .iter() .map(|key| ctx.strings.intern_bytes(key.as_ref())) .collect(); let values = collect_args(ctx, keys.len() as u32); Action::Push(Instr::Hhbc(Hhbc::NewStructDict(keys, values.into(), loc))) } Opcode::PopC => { ctx.pop(); Action::None } Opcode::String(value) => { let s1 = Constant::String(ctx.strings.intern_bytes(value.as_ref())); Action::Constant(s1) } }; match action { Action::Emit(opcode) => { ctx.emit(opcode); } Action::Constant(constant) => { ctx.emit_push_constant(constant); } Action::None => {} Action::Push(opcode) => { ctx.emit_push(opcode); } Action::Terminal(terminal) => { ctx.emit(Instr::Terminator(terminal)); return false; } } true } fn add_catch_work<'a, 'b>(ctx: &mut Context<'a, 'b>, mut tcid: TryCatchId) { loop { match tcid { TryCatchId::None => { // No catch target. return; } TryCatchId::Try(exid) => { // Catch block is the catch of this exid. ctx.add_work_bid(ctx.builder.func.ex_frames[&exid].catch_bid); return; } TryCatchId::Catch(exid) => { // Catch block is the catch of the parent. If our parent is a // Try(_) then we want its catch. If our parent is a Catch(_) // then we want its parent's stuff. tcid = ctx.builder.func.ex_frames[&exid].parent; } } } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/bc_to_ir/lib.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. #![feature(box_patterns)] mod class; mod constant; mod context; mod convert; mod func; mod instrs; mod sequence; mod types; pub use convert::bc_to_ir;
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/bc_to_ir/sequence.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::borrow::Cow; use std::ops::Range; use hhbc::Instruct; use ir::BlockId; use ir::BlockIdMap; use ir::ExFrameId; use ir::FuncBuilder; use ir::LocId; use ir::TryCatchId; use crate::context::Addr; use crate::context::AddrMap; use crate::context::LabelMap; /// A Sequence is a linear sequence of HHBC Instructs that doesn't cross either /// a Label or a Try/Catch boundary. /// /// (section 1) /// try { /// (section 2) /// label1: /// (section 3) /// label2: /// (section 4) /// } catch { /// (section 5) /// } /// (section 6) /// #[derive(Clone)] pub(crate) struct Sequence { pub kind: SequenceKind, pub bid: BlockId, pub tcid: TryCatchId, pub input_stack_size: Option<usize>, pub loc_id: LocId, pub next: Option<Addr>, pub range: Range<Addr>, } impl Sequence { pub(crate) fn compute( builder: &mut FuncBuilder<'_>, filename: ir::Filename, body_instrs: &[Instruct<'_>], ) -> (LabelMap<Addr>, BlockIdMap<Addr>, AddrMap<Sequence>) { let seq_builder = SeqBuilder { sequences: Default::default(), builder, filename, seq_addr: Addr::ENTRY, next_exid: ExFrameId::from_usize(1), tc_stack: Default::default(), }; seq_builder.compute(body_instrs) } } #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub(crate) enum SequenceKind { Normal, Catch, } struct SeqBuilder<'a, 'b> { sequences: Vec<(Addr, Sequence)>, builder: &'b mut FuncBuilder<'a>, filename: ir::Filename, seq_addr: Addr, next_exid: ExFrameId, tc_stack: Vec<TryCatchId>, } impl SeqBuilder<'_, '_> { fn add( &mut self, kind: SequenceKind, range: Range<Addr>, src_loc: &hhbc::SrcLoc, next: Option<Addr>, ) -> BlockId { let bid = self.builder.alloc_bid(); let loc_id = crate::context::add_loc(self.builder, self.filename, src_loc); let tcid = self.tc_stack.last().copied().unwrap_or_default(); self.builder.func.block_mut(bid).tcid = tcid; let sequence = Sequence { kind, bid, tcid, input_stack_size: None, loc_id, next, range, }; self.sequences.push((self.seq_addr, sequence)); bid } fn alloc_exid(&mut self) -> ExFrameId { let cur = self.next_exid; self.next_exid = ir::ExFrameId::from_usize(cur.as_usize() + 1); cur } fn compute( mut self, body_instrs: &[Instruct<'_>], ) -> (LabelMap<Addr>, BlockIdMap<Addr>, AddrMap<Sequence>) { let mut prev_addr: Addr = Addr::ENTRY; let mut label_to_addr: LabelMap<Addr> = Default::default(); let mut bid_to_addr: BlockIdMap<Addr> = Default::default(); let mut prev_kind = SequenceKind::Normal; let mut cur_src_loc: Cow<'_, hhbc::SrcLoc> = Cow::Owned(hhbc::SrcLoc::default()); let mut prev_src_loc = cur_src_loc.clone(); use hhbc::Pseudo; for (idx, instr) in body_instrs.iter().enumerate() { let idx = Addr::from_usize(idx); match *instr { Instruct::Pseudo(Pseudo::Label(label)) if idx == Addr::ENTRY => { // Special case - if the first Instr is a Label then we need // to include it in the first block. prev_addr = idx.incr(); label_to_addr.insert(label, idx); } Instruct::Pseudo( Pseudo::Label(_) | Pseudo::TryCatchBegin | Pseudo::TryCatchMiddle | Pseudo::TryCatchEnd, ) => { let bid = self.add(prev_kind, prev_addr..idx, &prev_src_loc, Some(idx)); bid_to_addr.insert(bid, self.seq_addr); if prev_kind == SequenceKind::Catch { // Now that we've created the catch target update the // ex_frame for it. let exid = self.tc_stack.last().unwrap().exid(); let parent = if self.tc_stack.len() > 1 { *self.tc_stack.get(self.tc_stack.len() - 2).unwrap() } else { TryCatchId::None }; self.builder.func.ex_frames.insert( exid, ir::func::ExFrame { parent, catch_bid: bid, }, ); } self.seq_addr = idx; prev_addr = idx.incr(); prev_kind = SequenceKind::Normal; prev_src_loc = cur_src_loc.clone(); match *instr { Instruct::Pseudo(Pseudo::Label(label)) => { label_to_addr.insert(label, idx); } Instruct::Pseudo(Pseudo::TryCatchBegin) => { let exid = self.alloc_exid(); self.tc_stack.push(TryCatchId::Try(exid)); } Instruct::Pseudo(Pseudo::TryCatchMiddle) => { let exid = self.tc_stack.pop().unwrap().exid(); self.tc_stack.push(TryCatchId::Catch(exid)); prev_kind = SequenceKind::Catch; } Instruct::Pseudo(Pseudo::TryCatchEnd) => { self.tc_stack.pop(); } _ => unreachable!(), } } Instruct::Pseudo(Pseudo::SrcLoc(ref src_loc)) => { cur_src_loc = Cow::Borrowed(src_loc); } _ => {} } } let range = prev_addr..Addr::from_usize(body_instrs.len()); self.add(SequenceKind::Normal, range, &prev_src_loc, None); let sequences: AddrMap<Sequence> = self.sequences.into_iter().collect(); (label_to_addr, bid_to_addr, sequences) } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/bc_to_ir/types.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use ffi::Maybe; use ffi::Str; use ir::BaseType; use ir::ClassId; use ir::StringInterner; use itertools::Itertools; use maplit::hashmap; use once_cell::sync::OnceCell; use crate::convert; use crate::types; pub(crate) fn convert_type<'a>(ty: &hhbc::TypeInfo<'a>, strings: &StringInterner) -> ir::TypeInfo { let user_type = ty.user_type.into_option(); let name = ty.type_constraint.name.into_option(); let constraint_ty = match name { // Checking for emptiness to filter out cases where the type constraint is not enforceable // (e.g. name = "", hint = type_const). Some(name) if !name.is_empty() => cvt_constraint_type(name, strings), Some(_) => BaseType::None, _ => user_type .as_ref() .and_then(|user_type| { use std::collections::HashMap; static UNCONSTRAINED_BY_NAME: OnceCell<HashMap<Str<'static>, BaseType>> = OnceCell::new(); let unconstrained_by_name = UNCONSTRAINED_BY_NAME.get_or_init(|| { hashmap! { ir::types::BUILTIN_NAME_VOID => BaseType::Void, ir::types::BUILTIN_NAME_SOFT_VOID => BaseType::Void, } }); unconstrained_by_name.get(user_type).cloned() }) .unwrap_or(BaseType::Mixed), }; ir::TypeInfo { user_type: user_type.map(|u| strings.intern_bytes(u.as_ref())), enforced: ir::EnforceableType { ty: constraint_ty, modifiers: ty.type_constraint.flags, }, } } pub(crate) fn convert_maybe_type<'a>( ty: Maybe<&hhbc::TypeInfo<'a>>, strings: &StringInterner, ) -> ir::TypeInfo { match ty { Maybe::Just(ty) => convert_type(ty, strings), Maybe::Nothing => ir::TypeInfo::empty(), } } fn cvt_constraint_type<'a>(name: Str<'a>, strings: &StringInterner) -> BaseType { use std::collections::HashMap; static CONSTRAINT_BY_NAME: OnceCell<HashMap<Str<'static>, BaseType>> = OnceCell::new(); let constraint_by_name = CONSTRAINT_BY_NAME.get_or_init(|| { hashmap! { ir::types::BUILTIN_NAME_ANY_ARRAY => BaseType::AnyArray, ir::types::BUILTIN_NAME_ARRAYKEY => BaseType::Arraykey, ir::types::BUILTIN_NAME_BOOL => BaseType::Bool, ir::types::BUILTIN_NAME_CLASSNAME => BaseType::Classname, ir::types::BUILTIN_NAME_DARRAY => BaseType::Darray, ir::types::BUILTIN_NAME_DICT => BaseType::Dict, ir::types::BUILTIN_NAME_FLOAT => BaseType::Float, ir::types::BUILTIN_NAME_INT => BaseType::Int, ir::types::BUILTIN_NAME_KEYSET => BaseType::Keyset, ir::types::BUILTIN_NAME_NONNULL => BaseType::Nonnull, ir::types::BUILTIN_NAME_NORETURN => BaseType::Noreturn, ir::types::BUILTIN_NAME_NOTHING => BaseType::Nothing, ir::types::BUILTIN_NAME_NULL => BaseType::Null, ir::types::BUILTIN_NAME_NUM => BaseType::Num, ir::types::BUILTIN_NAME_RESOURCE => BaseType::Resource, ir::types::BUILTIN_NAME_STRING => BaseType::String, ir::types::BUILTIN_NAME_THIS => BaseType::This, ir::types::BUILTIN_NAME_TYPENAME => BaseType::Typename, ir::types::BUILTIN_NAME_VARRAY => BaseType::Varray, ir::types::BUILTIN_NAME_VARRAY_OR_DARRAY => BaseType::VarrayOrDarray, ir::types::BUILTIN_NAME_VEC => BaseType::Vec, ir::types::BUILTIN_NAME_VEC_OR_DICT => BaseType::VecOrDict, } }); constraint_by_name.get(&name).cloned().unwrap_or_else(|| { let name = ClassId::new(strings.intern_bytes(name.as_ref())); BaseType::Class(name) }) } pub(crate) fn convert_typedef<'a>( td: &hhbc::Typedef<'a>, filename: ir::Filename, strings: &StringInterner, ) -> ir::Typedef { let hhbc::Typedef { name, attributes, type_info_union, type_structure, span, attrs, case_type, } = td; let loc = ir::SrcLoc::from_span(filename, span); let name = ClassId::from_hhbc(*name, strings); let attributes = attributes .iter() .map(|a| convert::convert_attribute(a, strings)) .collect_vec(); let type_info_union = type_info_union .iter() .map(|ti| types::convert_type(ti, strings)) .collect_vec(); let type_structure = convert::convert_typed_value(type_structure, strings); ir::Typedef { name, attributes, type_info_union, type_structure, loc, attrs: *attrs, case_type: *case_type, } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/bc_to_ir/b2i_macros/b2i_macros.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::collections::HashMap; use hhbc_gen::ImmType; use hhbc_gen::Inputs; use hhbc_gen::InstrFlags; use hhbc_gen::OpcodeData; use hhbc_gen::Outputs; use proc_macro2::Ident; use proc_macro2::TokenStream; use quote::quote; use quote::quote_spanned; use quote::ToTokens; use syn::parse::ParseStream; use syn::parse::Parser; use syn::spanned::Spanned; use syn::Arm; use syn::Attribute; use syn::Error; use syn::Expr; use syn::ExprAssign; use syn::ExprMacro; use syn::ExprMatch; use syn::ExprPath; use syn::Item; use syn::Macro; use syn::Pat; use syn::PatPath; use syn::Path; use syn::Result; use syn::Stmt; use syn::Token; /// This macro is used by the convert_opcode function to help it convert /// "standard" opcodes from HHVM's bytecode to IR Instrs. /// /// The macro looks in the main `match` of the function for patterns in the form: /// /// EnumSrc => simple!(EnumDst), /// EnumSrc => todo!(), /// /// When it sees a match arm in that form it rewrites it using the hhbc_gen /// data. As a concrete example: /// /// Opcode::ResolveFunc => simple!(Hhbc::ResolveFunc), /// /// is rewritten as: /// /// Opcode::ResolveFunc(ref str1) => { /// let str1 = /// ir::FunctionId::from_hhbc(*str1, ctx.strings); /// Action::Push(Instr::Hhbc(Hhbc::ResolveFunc(str1, ctx.loc))) /// } /// /// The macro is more complicated than just the basic rewriter because Rust /// doesn't allow you to use a macro as the pattern for a match statement - so /// we have to rewrite the whole function so we can rewrite the match itself. /// #[proc_macro_attribute] pub fn bc_to_ir( _attr: proc_macro::TokenStream, input: proc_macro::TokenStream, ) -> proc_macro::TokenStream { match build_bc_to_ir(input.into(), hhbc_gen::opcode_data()) { Ok(res) => res.into(), Err(err) => err.into_compile_error().into(), } } fn build_bc_to_ir(input: TokenStream, opcodes: &[OpcodeData]) -> Result<TokenStream> { let mut input = syn::parse2::<Item>(input)?; let opcodes: HashMap<String, &OpcodeData> = opcodes .iter() .map(|data| (data.name.to_owned(), data)) .collect(); let fn_item = match &mut input { Item::Fn(item) => item, _ => panic!("Unexpected item {}", debug_dump(input)), }; for stmt in fn_item.block.as_mut().stmts.iter_mut() { parse_stmt(stmt, &opcodes)?; } Ok(quote!(#input)) } fn debug_dump<T: std::fmt::Debug>(t: T) -> String { let mut s = format!("{:?}", t); s.truncate(10000); s } fn parse_stmt(stmt: &mut Stmt, opcodes: &HashMap<String, &OpcodeData>) -> Result<()> { match stmt { Stmt::Local(local) => { if has_bc_to_ir_attr(&mut local.attrs) { local.attrs = Vec::new(); if let Some(init) = local.init.as_mut() { let expr = init.1.as_mut(); match expr { Expr::Match(m) => process_match(m, opcodes)?, _ => { panic!("Unable to use #[bc_to_ir] on non-match."); } } } else { panic!("Unable to use #[bc_to_ir] on non-init assignment."); } } } Stmt::Item(..) | Stmt::Expr(..) | Stmt::Semi(..) => {} } Ok(()) } fn has_bc_to_ir_attr(attrs: &mut [Attribute]) -> bool { attrs .iter() .next() .map_or(false, |attr| attr.path.is_ident("bc_to_ir")) } fn expr_to_path(expr: Expr) -> Result<Path> { match expr { Expr::Path(ExprPath { path, .. }) => Ok(path), _ => Err(Error::new(expr.span(), "Simple path expected")), } } fn process_match(expr: &mut ExprMatch, opcodes: &HashMap<String, &OpcodeData>) -> Result<()> { for arm in expr.arms.iter_mut() { match &mut *arm.body { Expr::Macro(ExprMacro { mac: Macro { path, tokens, .. }, .. }) if path.is_ident("simple") => { let tokens = std::mem::take(tokens); *arm = (|parser: ParseStream<'_>| parse_convert_simple(parser, &arm.pat, opcodes)) .parse2(tokens)?; } Expr::Macro(ExprMacro { mac: Macro { path, tokens, .. }, .. }) if path.is_ident("todo") => { let tokens = std::mem::take(tokens); *arm = (|parser: ParseStream<'_>| parse_convert_todo(parser, &arm.pat, opcodes)) .parse2(tokens)?; } _ => {} } } Ok(()) } fn parse_opcode_pat<'a, 'b>( pat: &'a Pat, opcodes: &'b HashMap<String, &OpcodeData>, ) -> Result<(&'a Path, &'b OpcodeData)> { let span = pat.span(); let opcode_path = match pat { Pat::Path(PatPath { path, .. }) => path, _ => return Err(Error::new(span, "Simple path expected")), }; let (opcode_class, opcode_variant) = split_path2(opcode_path)?; if opcode_class != "Opcode" { return Err(Error::new( span, format!("Expected 'Opcode', not '{}'", opcode_class), )); } let data = if let Some(data) = opcodes.get(&opcode_variant) { data } else { return Err(Error::new( span, format!("Opcode '{}' not found", opcode_variant), )); }; Ok((opcode_path, data)) } fn parse_convert_simple( input: ParseStream<'_>, pat: &Pat, opcodes: &HashMap<String, &OpcodeData>, ) -> Result<Arm> { // simple!(Foo::Bar) ==> pat => Instr::Foo(Foo::Bar(loc)) // simple!(Foo::Bar, expr) ==> pat => Instr::Foo(Foo::Bar(expr, loc)) let (opcode_path, data) = parse_opcode_pat(pat, opcodes)?; let span = pat.span(); let instr_path: Path = input.parse()?; let (instr_class, _instr_variant) = split_path2(&instr_path)?; let is_constant = instr_class == "Constant"; let is_terminator = instr_class == "Terminator"; let instr_class = Ident::new(&instr_class, instr_path.span()); let mut extra = Vec::new(); while !input.is_empty() { input.parse::<Token![,]>()?; let expr = input.parse::<Expr>()?; match expr { Expr::Assign(ExprAssign { left, right: _, .. }) => { let left = expr_to_path(*left)?; return Err(Error::new(left.span(), "Unexpected tag")); } Expr::Path(_) | Expr::Lit(_) => { extra.push(expr); } _ => { return Err(Error::new(span, "Unhandled input")); } } } let mut imms_out: Vec<&str> = data.immediates.iter().map(|(a, _)| *a).collect(); let mut pops = Vec::new(); let mut params: Vec<TokenStream> = Vec::new(); let mut conv = Vec::new(); match &data.inputs { Inputs::NOV => {} Inputs::Fixed(inputs) => { let mut inputs: Vec<Ident> = (0..inputs.len()) .map(|i| Ident::new(&format!("s{}", i + 1), span)) .collect(); pops.extend(inputs.iter().rev().map(|id| quote!(let #id = ctx.pop();))); if inputs.len() == 1 { params.push(inputs.pop().unwrap().to_token_stream()); } else { params.push(quote!([#(#inputs),*])); }; } Inputs::CMany => { pops.push(quote!(let args = collect_args(ctx, arg1).into();)); *imms_out.iter_mut().find(|imm| **imm == "arg1").unwrap() = "args"; } Inputs::CMFinal(..) | Inputs::CUMany | Inputs::FCall { .. } | Inputs::MFinal | Inputs::SMany => { return Err(Error::new( span, format!("Unhandled conversion: {:?}", data.inputs), )); } }; let mut match_pats = Vec::new(); for (name, ty) in &data.immediates { let imm = Ident::new(name, span); let mut convert = |converter: TokenStream| { match_pats.push(quote!(ref #imm)); conv.push(quote_spanned!(span=> let #imm = #converter; )); }; let strings = quote_spanned!(span=> ctx.strings); match ty { ImmType::OAL(n) if *n == "ClassName" => { convert(quote_spanned!(span=> ir::ClassId::from_hhbc(*#imm, #strings) )); } ImmType::OAL(n) if *n == "ConstName" => { convert(quote_spanned!(span=> ir::ConstId::from_hhbc(*#imm, #strings) )); } ImmType::OAL(n) if *n == "FunctionName" => { convert(quote_spanned!(span=> ir::FunctionId::from_hhbc(*#imm, #strings) )); } ImmType::OAL(n) if *n == "MethodName" => { convert(quote_spanned!(span=> ir::MethodId::from_hhbc(*#imm, #strings) )); } ImmType::OAL(n) if *n == "ParamName" => { convert(quote_spanned!(span=> ir::ParamId::from_hhbc(#imm, #strings) )); } ImmType::OAL(n) if *n == "PropName" => { convert(quote_spanned!(span=> ir::PropId::from_hhbc(*#imm, #strings) )); } ImmType::AA | ImmType::ARR(_) | ImmType::BA | ImmType::BA2 | ImmType::BLA | ImmType::DA | ImmType::DUMMY | ImmType::FCA | ImmType::I64A | ImmType::IA | ImmType::ITA | ImmType::IVA | ImmType::KA | ImmType::NA | ImmType::OA(_) | ImmType::OAL(_) | ImmType::RATA | ImmType::SA | ImmType::SLA | ImmType::VSA => { match_pats.push(imm.to_token_stream()); } ImmType::ILA | ImmType::LA | ImmType::NLA => { convert(quote_spanned!(span=> convert_local(ctx, #imm) )); } ImmType::LAR => { convert(quote_spanned!(span=> convert_local_range(ctx, #imm) )); } } } params.extend( imms_out .into_iter() .map(|name| Ident::new(name, span).to_token_stream()), ); params.extend(extra.iter().map(ToTokens::to_token_stream)); if !is_constant { params.push(quote!(ctx.loc)); } let pat = if data.flags.contains(InstrFlags::AS_STRUCT) { todo!("AS_STRUCT"); } else { build_match_pat(opcode_path, match_pats)? }; let cons = { match &data.outputs { Outputs::NOV => { if is_terminator { quote!(Action::Terminal(#instr_path(#(#params),*))) } else { quote!(Action::Emit(Instr::#instr_class(#instr_path(#(#params),*)))) } } Outputs::Fixed(outputs) if outputs.len() == 1 => { if is_constant { if params.is_empty() { quote!(Action::Constant(#instr_path)) } else { quote!(Action::Constant(#instr_path(#(#params),*))) } } else if is_terminator { quote!(Action::Terminal(#instr_path(#(#params),*))) } else { quote!(Action::Push(Instr::#instr_class(#instr_path(#(#params),*)))) } } outputs => { return Err(Error::new( span, format!("Unhandled outputs: {:?}", outputs), )); } } }; let arm = syn::parse2::<Arm>(quote!(#pat => { #(#pops)* #(#conv)* #cons }))?; Ok(arm) } fn parse_convert_todo( _input: ParseStream<'_>, pat: &Pat, opcodes: &HashMap<String, &OpcodeData>, ) -> Result<Arm> { let (_, data) = parse_opcode_pat(pat, opcodes)?; let span = pat.span(); let pat = pat.to_token_stream(); let msg = format!("Unimplemented opcode '{}'", pat); let tokens = if data.immediates.is_empty() { quote_spanned!(span=> #pat => todo!(#msg),) } else { quote_spanned!(span=> #pat(..) => todo!(#msg),) }; let arm = syn::parse2::<Arm>(tokens)?; Ok(arm) } fn build_match_pat(opcode: &Path, match_pats: Vec<TokenStream>) -> Result<Pat> { let toks = if match_pats.is_empty() { opcode.to_token_stream() } else { quote!(#opcode ( #(#match_pats),* )) }; syn::parse2::<Pat>(toks) } fn split_path(path: &Path) -> Vec<String> { let mut res = Vec::new(); for seg in path.segments.iter() { res.push(format!("{}", seg.ident)); } res } fn split_path2(path: &Path) -> Result<(String, String)> { let v = split_path(path); if v.len() != 2 { Err(Error::new(path.span(), "Expected A::B")) } else { let mut it = v.into_iter(); let a = it.next().unwrap(); let b = it.next().unwrap(); Ok((a, b)) } }
TOML
hhvm/hphp/hack/src/hackc/ir/conversions/bc_to_ir/b2i_macros/Cargo.toml
# @generated by autocargo [package] name = "b2i_macros" version = "0.0.0" edition = "2021" [lib] path = "b2i_macros.rs" test = false doctest = false proc-macro = true [dependencies] hhbc-gen = { version = "0.0.0", path = "../../../../../../../tools/hhbc-gen" } proc-macro2 = { version = "1.0.64", features = ["span-locations"] } quote = "1.0.29" syn = { version = "1.0.109", features = ["extra-traits", "fold", "full", "visit", "visit-mut"] }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/ir_to_bc/adata.rs
use std::sync::Arc; use ffi::Slice; use hash::HashMap; use crate::strings::StringCache; /// Builder for hhbc::Unit.adata. pub(crate) struct AdataCache<'a> { alloc: &'a bumpalo::Bump, adata: Vec<hhbc::Adata<'a>>, lookup: HashMap<Arc<ir::TypedValue>, usize>, } impl<'a> AdataCache<'a> { pub(crate) fn new(alloc: &'a bumpalo::Bump) -> Self { Self { alloc, adata: Default::default(), lookup: Default::default(), } } pub(crate) fn intern( &mut self, tv: Arc<ir::TypedValue>, strings: &StringCache<'a>, ) -> hhbc::AdataId<'a> { let idx = self.lookup.entry(tv).or_insert_with_key(|tv| { let idx = self.adata.len(); let id = hhbc::AdataId::new(ffi::Str::new_str(self.alloc, &format!("A_{}", idx))); let value = crate::convert::convert_typed_value(tv, strings); self.adata.push(hhbc::Adata { id, value }); idx }); self.adata[*idx].id } pub(crate) fn finish(self) -> Slice<'a, hhbc::Adata<'a>> { Slice::fill_iter(self.alloc, self.adata.into_iter()) } }
TOML
hhvm/hphp/hack/src/hackc/ir/conversions/ir_to_bc/Cargo.toml
# @generated by autocargo [package] name = "ir_to_bc" version = "0.0.0" edition = "2021" [lib] path = "lib.rs" [dependencies] bumpalo = { version = "3.11.1", features = ["collections"] } dashmap = { version = "5.4", features = ["rayon", "serde"] } ffi = { version = "0.0.0", path = "../../../../utils/ffi" } hash = { version = "0.0.0", path = "../../../../utils/hash" } hhbc = { version = "0.0.0", path = "../../../hhbc/cargo/hhbc" } instruction_sequence = { version = "0.0.0", path = "../../../emitter/cargo/instruction_sequence" } ir = { version = "0.0.0", path = "../.." } itertools = "0.10.3" log = { version = "0.4.17", features = ["kv_unstable", "kv_unstable_std"] } smallvec = { version = "1.6.1", features = ["serde", "specialization", "union"] } stack_depth = { version = "0.0.0", path = "../../../utils/cargo/stack_depth" }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/ir_to_bc/class.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use ffi::Maybe; use ffi::Slice; use crate::convert; use crate::convert::UnitBuilder; use crate::strings::StringCache; use crate::types; pub(crate) fn convert_class<'a>( alloc: &'a bumpalo::Bump, unit: &mut UnitBuilder<'a>, class: ir::Class<'a>, strings: &StringCache<'a>, ) { let ir::Class { attributes, base, constants, ctx_constants, doc_comment, enum_type, enum_includes, flags, implements, methods, name, properties, requirements, src_loc, type_constants, upper_bounds, uses, } = class; let requirements: Slice<'a, hhbc::Requirement<'a>> = Slice::fill_iter( alloc, (requirements.iter()).map(|ir::class::Requirement { name, kind }| { let name = strings.lookup_class_name(*name); hhbc::Requirement { name, kind: *kind } }), ); let ctx_constants = Slice::fill_iter( alloc, ctx_constants .iter() .map(|ctx| convert_ctx_constant(alloc, ctx)), ); let enum_includes = Slice::fill_iter( alloc, enum_includes .into_iter() .map(|id| strings.lookup_class_name(id)), ); let enum_type: Maybe<_> = enum_type .as_ref() .map(|et| types::convert(et, strings).unwrap()) .into(); let type_constants = Slice::fill_iter( alloc, type_constants .into_iter() .map(|tc| convert_type_constant(tc, strings)), ); let upper_bounds = Slice::fill_iter( alloc, upper_bounds.iter().map(|(name, tys)| hhbc::UpperBound { name: *name, bounds: Slice::fill_iter( alloc, tys.iter().map(|ty| types::convert(ty, strings).unwrap()), ), }), ); let base = base.map(|base| strings.lookup_class_name(base)).into(); let implements = Slice::fill_iter( alloc, implements .iter() .map(|interface| strings.lookup_class_name(*interface)), ); let name = strings.lookup_class_name(name); let uses = Slice::fill_iter( alloc, uses.into_iter().map(|use_| strings.lookup_class_name(use_)), ); let methods = Slice::fill_iter( alloc, methods .into_iter() .map(|method| crate::func::convert_method(method, strings, &mut unit.adata_cache)), ); let class = hhbc::Class { attributes: convert::convert_attributes(attributes, strings), base, constants: Slice::fill_iter( alloc, constants .into_iter() .map(|c| crate::constant::convert_hack_constant(c, strings)), ), ctx_constants, doc_comment: doc_comment.into(), enum_includes, enum_type, flags, implements, methods, name, properties: Slice::fill_iter( alloc, properties .into_iter() .map(|prop| convert_property(prop, strings)), ), requirements, span: src_loc.to_span(), type_constants, upper_bounds, uses, }; unit.classes.push(class); } fn convert_property<'a>(src: ir::Property<'a>, strings: &StringCache<'a>) -> hhbc::Property<'a> { hhbc::Property { name: strings.lookup_prop_name(src.name), flags: src.flags, attributes: convert::convert_attributes(src.attributes, strings), visibility: src.visibility, initial_value: src .initial_value .map(|tv| convert::convert_typed_value(&tv, strings)) .into(), type_info: types::convert(&src.type_info, strings).unwrap(), doc_comment: src.doc_comment, } } fn convert_ctx_constant<'a>( alloc: &'a bumpalo::Bump, ctx: &ir::CtxConstant<'a>, ) -> hhbc::CtxConstant<'a> { hhbc::CtxConstant { name: ctx.name, recognized: Slice::fill_iter(alloc, ctx.recognized.iter().cloned()), unrecognized: Slice::fill_iter(alloc, ctx.unrecognized.iter().cloned()), is_abstract: ctx.is_abstract, } } fn convert_type_constant<'a>( tc: ir::TypeConstant<'a>, strings: &StringCache<'a>, ) -> hhbc::TypeConstant<'a> { hhbc::TypeConstant { name: tc.name, initializer: tc .initializer .map(|init| convert::convert_typed_value(&init, strings)) .into(), is_abstract: tc.is_abstract, } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/ir_to_bc/constant.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use hhbc::Constant; use crate::convert; use crate::strings::StringCache; pub(crate) fn convert_hack_constant<'a>( constant: ir::HackConstant, strings: &StringCache<'a>, ) -> Constant<'a> { let ir::HackConstant { name, value, attrs } = constant; let value = value .map(|v| convert::convert_typed_value(&v, strings)) .into(); let name = strings.lookup_const_name(name); Constant { name, value, attrs } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/ir_to_bc/convert.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::sync::Arc; use ffi::Maybe; use ffi::Slice; use hhbc::Fatal; use crate::adata::AdataCache; use crate::strings::StringCache; /// Convert an ir::Unit to a hhbc::Unit /// /// Most of the outer structure of the hhbc::Unit maps 1:1 with ir::Unit. As a /// result the "interesting" work is in the conversion of the IR to bytecode /// when converting functions and methods (see `convert_func` in func.rs). /// pub fn ir_to_bc<'a>(alloc: &'a bumpalo::Bump, ir_unit: ir::Unit<'a>) -> hhbc::Unit<'a> { let strings = StringCache::new(alloc, Arc::clone(&ir_unit.strings)); let mut unit = UnitBuilder::new_in(alloc); for cls in ir_unit.classes.into_iter() { crate::class::convert_class(alloc, &mut unit, cls, &strings); } for function in ir_unit.functions.into_iter() { crate::func::convert_function(&mut unit, function, &strings); } let mut unit = unit.finish(); unit.file_attributes = convert_attributes(ir_unit.file_attributes, &strings); unit.typedefs = Slice::fill_iter( alloc, ir_unit .typedefs .into_iter() .map(|td| crate::types::convert_typedef(td, &strings)), ); unit.constants = Slice::fill_iter( alloc, ir_unit .constants .into_iter() .map(|c| crate::constant::convert_hack_constant(c, &strings)), ); unit.modules = Slice::fill_iter( alloc, ir_unit.modules.into_iter().map(|module| hhbc::Module { attributes: convert_attributes(module.attributes, &strings), name: strings.lookup_class_name(module.name), span: module.src_loc.to_span(), doc_comment: module.doc_comment.into(), exports: Maybe::Nothing, // TODO imports: Maybe::Nothing, // TODO }), ); unit.module_use = ir_unit.module_use.into(); unit.symbol_refs = convert_symbol_refs(alloc, &ir_unit.symbol_refs); if let Some(ir::Fatal { op, loc, message }) = ir_unit.fatal.as_ref() { let op = match *op { ir::FatalOp::Parse => hhbc::FatalOp::Parse, ir::FatalOp::Runtime => hhbc::FatalOp::Runtime, ir::FatalOp::RuntimeOmitFrame => hhbc::FatalOp::RuntimeOmitFrame, _ => unreachable!(), }; unit.fatal = Maybe::Just(Fatal { op, loc: loc.to_hhbc(), message: ffi::Str::new_slice(alloc, message), }); } unit } pub(crate) struct UnitBuilder<'a> { pub adata_cache: AdataCache<'a>, pub functions: bumpalo::collections::Vec<'a, hhbc::Function<'a>>, pub classes: bumpalo::collections::Vec<'a, hhbc::Class<'a>>, } impl<'a> UnitBuilder<'a> { fn new_in(alloc: &'a bumpalo::Bump) -> Self { Self { adata_cache: AdataCache::new(alloc), classes: bumpalo::collections::Vec::new_in(alloc), functions: bumpalo::collections::Vec::new_in(alloc), } } fn finish(self) -> hhbc::Unit<'a> { hhbc::Unit { adata: self.adata_cache.finish(), functions: self.functions.into_bump_slice().into(), classes: self.classes.into_bump_slice().into(), typedefs: Default::default(), file_attributes: Default::default(), modules: Default::default(), module_use: Maybe::Nothing, symbol_refs: Default::default(), constants: Default::default(), fatal: Default::default(), missing_symbols: Default::default(), error_symbols: Default::default(), } } } fn convert_symbol_refs<'a>( alloc: &'a bumpalo::Bump, symbol_refs: &ir::unit::SymbolRefs<'a>, ) -> hhbc::SymbolRefs<'a> { let classes = Slice::fill_iter(alloc, symbol_refs.classes.iter().cloned()); let constants = Slice::fill_iter(alloc, symbol_refs.constants.iter().cloned()); let functions = Slice::fill_iter(alloc, symbol_refs.functions.iter().cloned()); let includes = Slice::fill_iter(alloc, symbol_refs.includes.iter().cloned()); hhbc::SymbolRefs { classes, constants, functions, includes, } } pub(crate) fn convert_attributes<'a>( attrs: Vec<ir::Attribute>, strings: &StringCache<'a>, ) -> Slice<'a, hhbc::Attribute<'a>> { Slice::fill_iter( strings.alloc, attrs.into_iter().map(|attr| { let arguments = Slice::fill_iter( strings.alloc, attr.arguments .into_iter() .map(|arg| convert_typed_value(&arg, strings)), ); hhbc::Attribute { name: strings.lookup_class_name(attr.name).as_ffi_str(), arguments, } }), ) } pub(crate) fn convert_typed_value<'a>( tv: &ir::TypedValue, strings: &StringCache<'a>, ) -> hhbc::TypedValue<'a> { match *tv { ir::TypedValue::Uninit => hhbc::TypedValue::Uninit, ir::TypedValue::Int(v) => hhbc::TypedValue::Int(v), ir::TypedValue::Bool(v) => hhbc::TypedValue::Bool(v), ir::TypedValue::Float(v) => hhbc::TypedValue::Float(v), ir::TypedValue::String(v) => hhbc::TypedValue::String(strings.lookup_ffi_str(v)), ir::TypedValue::LazyClass(v) => { hhbc::TypedValue::LazyClass(strings.lookup_class_name(v).as_ffi_str()) } ir::TypedValue::Null => hhbc::TypedValue::Null, ir::TypedValue::Vec(ref vs) => hhbc::TypedValue::Vec(Slice::fill_iter( strings.alloc, vs.iter().map(|v| convert_typed_value(v, strings)), )), ir::TypedValue::Keyset(ref vs) => hhbc::TypedValue::Keyset(Slice::fill_iter( strings.alloc, vs.iter().map(|v| convert_array_key(v, strings)), )), ir::TypedValue::Dict(ref vs) => hhbc::TypedValue::Dict(Slice::fill_iter( strings.alloc, vs.iter().map(|(k, v)| { let key = convert_array_key(k, strings); let value = convert_typed_value(v, strings); hhbc::Entry { key, value } }), )), } } pub(crate) fn convert_array_key<'a>( tv: &ir::ArrayKey, strings: &StringCache<'a>, ) -> hhbc::TypedValue<'a> { match *tv { ir::ArrayKey::Int(v) => hhbc::TypedValue::Int(v), ir::ArrayKey::LazyClass(v) => { hhbc::TypedValue::LazyClass(strings.lookup_class_name(v).as_ffi_str()) } ir::ArrayKey::String(v) => hhbc::TypedValue::String(strings.lookup_ffi_str(v)), } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/ir_to_bc/emitter.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::collections::VecDeque; use std::fmt::Display; use std::sync::Arc; use ffi::Slice; use ffi::Str; use hash::HashMap; use hhbc::Dummy; use hhbc::Instruct; use hhbc::Opcode; use hhbc::Pseudo; use instruction_sequence::InstrSeq; use ir::instr; use ir::instr::HasLoc; use ir::instr::HasLocals; use ir::instr::IrToBc; use ir::newtype::ConstantIdMap; use ir::print::FmtRawVid; use ir::print::FmtSep; use ir::BlockId; use ir::BlockIdMap; use ir::FCallArgsFlags; use ir::LocalId; use itertools::Itertools; use log::trace; use crate::adata::AdataCache; use crate::ex_frame::BlockIdOrExFrame; use crate::ex_frame::ExFrame; use crate::strings::StringCache; pub(crate) fn emit_func<'a>( func: &ir::Func<'a>, labeler: &mut Labeler, strings: &StringCache<'a>, adata_cache: &mut AdataCache<'a>, ) -> (InstrSeq<'a>, Vec<Str<'a>>) { let adata_id_map = func .constants .iter() .enumerate() .filter_map(|(idx, constant)| { let cid = ir::ConstantId::from_usize(idx); match constant { ir::Constant::Array(tv) => { let id = adata_cache.intern(Arc::clone(tv), strings); let kind = match **tv { ir::TypedValue::Dict(_) => AdataKind::Dict, ir::TypedValue::Keyset(_) => AdataKind::Keyset, ir::TypedValue::Vec(_) => AdataKind::Vec, _ => unreachable!(), }; Some((cid, (id, kind))) } _ => None, } }) .collect(); let mut ctx = InstrEmitter::new(func, labeler, strings, &adata_id_map); // Collect the Blocks, grouping them into TryCatch sections. let root = crate::ex_frame::collect_tc_sections(func); ctx.convert_frame_vec(root); // Collect the decl_vars - these are all the named locals after the params. let decl_vars: Vec<Str<'a>> = ctx .locals .iter() .sorted_by_key(|(_, v)| *v) .filter_map(|(k, _)| match *k { LocalId::Named(name) => Some(strings.lookup_ffi_str(name)), LocalId::Unnamed(_) => None, }) .skip(func.params.len()) .collect(); (InstrSeq::List(ctx.instrs), decl_vars) } /// Use to look up a ConstantId and get the AdataId and AdataKind for that /// ConstantId. type AdataIdMap<'a> = ConstantIdMap<(hhbc::AdataId<'a>, AdataKind)>; /// Used for adata_id_map - the kind of the underlying array. Storing this in /// AdataIdMap means we don't have to pass around a &Unit just to look up what /// kind of array it represents. enum AdataKind { Dict, Keyset, Vec, } /// Helper struct for converting ir::BlockId to hhbc::Label. pub(crate) struct Labeler { bid_to_label: BlockIdMap<hhbc::Label>, label_to_bid: HashMap<hhbc::Label, BlockId>, next_label_id: u32, } impl Labeler { pub(crate) fn new(func: &ir::Func<'_>) -> Self { let mut labeler = Self { bid_to_label: Default::default(), label_to_bid: Default::default(), next_label_id: 0, }; labeler.prealloc_labels(func); labeler } // Go through the blocks and for any with well-known names assign those // names now. If we don't do this on init then we're liable to accidentally // use a name that we'll need later on. fn prealloc_labels(&mut self, func: &ir::Func<'_>) { fn pname_to_label(pname: &str) -> Option<hhbc::Label> { if let Some(label) = pname.strip_prefix('L') { label.parse::<u32>().ok().map(hhbc::Label) } else if let Some(label) = pname.strip_prefix("DV") { label.parse::<u32>().ok().map(hhbc::Label) } else { None } } for (bid, label) in func .block_ids() .map(|bid| (bid, func.block(bid))) .filter_map(|(bid, block)| block.pname_hint.as_ref().map(|pname| (bid, pname))) .filter_map(|(bid, pname)| pname_to_label(pname).map(|label| (bid, label))) { if let std::collections::hash_map::Entry::Vacant(e) = self.label_to_bid.entry(label) { self.bid_to_label.insert(bid, label); e.insert(bid); self.next_label_id = std::cmp::max(self.next_label_id, label.0 + 1); } } } fn get_bid(&self, bid: BlockId) -> Option<hhbc::Label> { self.bid_to_label.get(&bid).copied() } pub(crate) fn lookup_bid(&self, bid: BlockId) -> hhbc::Label { self.bid_to_label[&bid] } fn lookup_label(&self, label: hhbc::Label) -> Option<BlockId> { self.label_to_bid.get(&label).copied() } fn lookup_or_insert_bid(&mut self, bid: BlockId) -> hhbc::Label { *self.bid_to_label.entry(bid).or_insert_with(|| { let label = hhbc::Label(self.next_label_id); self.next_label_id += 1; self.label_to_bid.insert(label, bid); label }) } } fn compute_block_entry_edges(func: &ir::Func<'_>) -> BlockIdMap<usize> { let mut edges = BlockIdMap::default(); for param in &func.params { if let Some(dv) = param.default_value.as_ref() { edges.entry(dv.init).and_modify(|e| *e += 1).or_insert(1); } } for bid in func.block_ids() { edges.entry(bid).or_insert(0); for &edge in func.edges(bid) { edges.entry(edge).and_modify(|e| *e += 1).or_insert(1); } } edges } pub(crate) struct InstrEmitter<'a, 'b> { // How many blocks jump to this one? block_entry_edges: BlockIdMap<usize>, func: &'b ir::Func<'a>, instrs: Vec<Instruct<'a>>, labeler: &'b mut Labeler, loc_id: ir::LocId, strings: &'b StringCache<'a>, locals: HashMap<LocalId, hhbc::Local>, adata_id_map: &'b AdataIdMap<'a>, } fn convert_indexes_to_bools<'a>( alloc: &'a bumpalo::Bump, total_len: usize, indexes: Option<&[u32]>, ) -> Slice<'a, bool> { let mut buf: Vec<bool> = Vec::with_capacity(total_len); if !indexes.map_or(true, |indexes| indexes.is_empty()) { buf.resize(total_len, false); if let Some(indexes) = indexes { for &idx in indexes.iter() { buf[idx as usize] = true; } } } Slice::from_vec(alloc, buf) } impl<'a, 'b> InstrEmitter<'a, 'b> { fn new( func: &'b ir::Func<'a>, labeler: &'b mut Labeler, strings: &'b StringCache<'a>, adata_id_map: &'b AdataIdMap<'a>, ) -> Self { let locals = Self::prealloc_locals(func); Self { block_entry_edges: compute_block_entry_edges(func), func, instrs: Vec::new(), labeler, loc_id: ir::LocId::NONE, locals, strings, adata_id_map, } } fn prealloc_locals(func: &'b ir::Func<'a>) -> HashMap<LocalId, hhbc::Local> { let mut next_local_idx = 0; // The parameters are required to be the first named locals. We can't // control that. let mut locals: HashMap<LocalId, hhbc::Local> = func .params .iter() .enumerate() .map(|(_, param)| { let name = LocalId::Named(param.name); let local = hhbc::Local::from_usize(next_local_idx); next_local_idx += 1; (name, local) }) .collect(); trace!("Parameters end at {}", next_local_idx); // Now go through and collect the named and unnamed locals. Once we know // how many named locals there are we can fixup the unnamed ones. for instr in func.body_instrs() { for lid in instr.locals() { match lid { LocalId::Named(_) => { locals.entry(*lid).or_insert_with(|| { let local = hhbc::Local::from_usize(next_local_idx); next_local_idx += 1; local }); } LocalId::Unnamed(idx) => { locals .entry(*lid) .or_insert_with(|| hhbc::Local::from_usize(idx.as_usize())); } } } } trace!("Named locals end at {}", next_local_idx); // Now that we know the count of named locals we can update the unnamed // locals. for (k, v) in locals.iter_mut() { if matches!(k, LocalId::Unnamed(_)) { v.idx += next_local_idx as u32; } } locals } fn push_opcode(&mut self, opcode: Opcode<'a>) { self.instrs.push(Instruct::Opcode(opcode)); } fn lookup_local(&mut self, lid: LocalId) -> hhbc::Local { if let Some(local) = self.locals.get(&lid) { *local } else { panic!("Unmapped LocalId {:?}", lid); } } fn emit_call_helper(&mut self, call: &instr::Call, async_eager_target: Option<hhbc::Label>) { let fcall_args = { use hhbc::FCallArgs; let mut num_args = call.args().len() as u32; num_args -= call.flags.contains(FCallArgsFlags::HasUnpack) as u32; num_args -= call.flags.contains(FCallArgsFlags::HasGenerics) as u32; let num_rets = call.num_rets; let inouts = convert_indexes_to_bools( self.strings.alloc, num_args as usize, call.inouts.as_deref(), ); let readonly = convert_indexes_to_bools( self.strings.alloc, num_args as usize, call.readonly.as_deref(), ); let context = self.strings.lookup_ffi_str(call.context); let async_eager_target = if let Some(label) = async_eager_target { label } else { hhbc::Label::INVALID }; FCallArgs { flags: call.flags, async_eager_target, num_args, num_rets, inouts, readonly, context, } }; let hint = Str::empty(); let instr = match &call.detail { ir::instr::CallDetail::FCallClsMethod { log } => { Opcode::FCallClsMethod(fcall_args, hint, *log) } ir::instr::CallDetail::FCallClsMethodD { clsid, method } => { let class = self.strings.lookup_class_name(*clsid); let method = self.strings.lookup_method_name(*method); Opcode::FCallClsMethodD(fcall_args, class, method) } ir::instr::CallDetail::FCallClsMethodM { method, log } => { let method = self.strings.lookup_method_name(*method); Opcode::FCallClsMethodM(fcall_args, hint, *log, method) } ir::instr::CallDetail::FCallClsMethodS { clsref } => { Opcode::FCallClsMethodS(fcall_args, hint, *clsref) } ir::instr::CallDetail::FCallClsMethodSD { method, clsref } => { let method = self.strings.lookup_method_name(*method); Opcode::FCallClsMethodSD(fcall_args, hint, *clsref, method) } ir::instr::CallDetail::FCallCtor => Opcode::FCallCtor(fcall_args, hint), ir::instr::CallDetail::FCallFunc => Opcode::FCallFunc(fcall_args), ir::instr::CallDetail::FCallFuncD { func } => { Opcode::FCallFuncD(fcall_args, self.strings.lookup_function_name(*func)) } ir::instr::CallDetail::FCallObjMethod { flavor } => { Opcode::FCallObjMethod(fcall_args, hint, *flavor) } ir::instr::CallDetail::FCallObjMethodD { flavor, method } => { let method = self.strings.lookup_method_name(*method); Opcode::FCallObjMethodD(fcall_args, hint, *flavor, method) } }; self.push_opcode(instr); } fn emit_call(&mut self, call: &instr::Call) { self.emit_call_helper(call, None); } fn emit_call_async(&mut self, call: &instr::Call, targets: &[BlockId; 2]) { let label = self.labeler.lookup_or_insert_bid(targets[1]); self.emit_call_helper(call, Some(label)); self.jump_to(targets[0]); } fn jump_to(&mut self, bid: BlockId) { if bid != BlockId::NONE { let label = self.labeler.lookup_or_insert_bid(bid); self.push_opcode(Opcode::Enter(label)); } } fn convert_local_range(&mut self, slice: &[LocalId]) -> hhbc::LocalRange { let locals: Vec<hhbc::Local> = slice.iter().map(|lid| self.lookup_local(*lid)).collect(); if let Some(&start) = locals.first() { let len = locals.len() as u32; // At this point pusher should have aligned stuff so that the // variables are all contiguous... locals.iter().reduce(|x, y| { assert!( x.as_usize() + 1 == y.as_usize(), "non-linear locals: [{}]", locals .iter() .map(ToString::to_string) .collect::<Vec<_>>() .join(", ") ); y }); hhbc::LocalRange { start, len } } else { hhbc::LocalRange { start: hhbc::Local::INVALID, len: 0, } } } /// This is the emitter for HHBC opcodes. At this point the stack values /// have been pushed and we just need to emit the correct opcode for the /// pending instruction (along with its immediates). fn emit_hhbc(&mut self, hhbc: &instr::Hhbc) { use instr::Hhbc; let opcode = match *hhbc { Hhbc::AKExists(..) => Opcode::AKExists, Hhbc::Add(..) => Opcode::Add, Hhbc::AddElemC(..) => Opcode::AddElemC, Hhbc::AddNewElemC(..) => Opcode::AddNewElemC, Hhbc::ArrayIdx(..) => Opcode::ArrayIdx, Hhbc::ArrayMarkLegacy(..) => Opcode::ArrayMarkLegacy, Hhbc::ArrayUnmarkLegacy(..) => Opcode::ArrayUnmarkLegacy, Hhbc::Await(..) => Opcode::Await, Hhbc::AwaitAll(ref locals, _) => { let locals = self.convert_local_range(locals); Opcode::AwaitAll(locals) } Hhbc::BareThis(op, _) => Opcode::BareThis(op), Hhbc::BitAnd(..) => Opcode::BitAnd, Hhbc::BitNot(..) => Opcode::BitNot, Hhbc::BitOr(..) => Opcode::BitOr, Hhbc::BitXor(..) => Opcode::BitXor, Hhbc::CGetG(..) => Opcode::CGetG, Hhbc::CGetL(lid, _) => { let local = self.lookup_local(lid); Opcode::CGetL(local) } Hhbc::CGetQuietL(lid, _) => { let local = self.lookup_local(lid); Opcode::CGetQuietL(local) } Hhbc::CGetS(_, readonly, _) => Opcode::CGetS(readonly), Hhbc::CUGetL(lid, _) => { let local = self.lookup_local(lid); Opcode::CUGetL(local) } Hhbc::CastBool(..) => Opcode::CastBool, Hhbc::CastDict(..) => Opcode::CastDict, Hhbc::CastDouble(..) => Opcode::CastDouble, Hhbc::CastInt(..) => Opcode::CastInt, Hhbc::CastKeyset(..) => Opcode::CastKeyset, Hhbc::CastString(..) => Opcode::CastString, Hhbc::CastVec(..) => Opcode::CastVec, Hhbc::CheckClsReifiedGenericMismatch(..) => Opcode::CheckClsReifiedGenericMismatch, Hhbc::CheckClsRGSoft(..) => Opcode::CheckClsRGSoft, Hhbc::ChainFaults(..) => Opcode::ChainFaults, Hhbc::CheckProp(prop, _) => { let prop = self.strings.lookup_prop_name(prop); Opcode::CheckProp(prop) } Hhbc::CheckThis(_) => Opcode::CheckThis, Hhbc::ClassGetC(_, _) => Opcode::ClassGetC, Hhbc::ClassGetTS(_, _) => Opcode::ClassGetTS, Hhbc::ClassHasReifiedGenerics(_, _) => Opcode::ClassHasReifiedGenerics, Hhbc::ClassName(..) => Opcode::ClassName, Hhbc::Clone(..) => Opcode::Clone, Hhbc::ClsCns(_, id, _) => { let id = self.strings.lookup_const_name(id); Opcode::ClsCns(id) } Hhbc::ClsCnsD(id, clsid, _) => { let clsid = self.strings.lookup_class_name(clsid); let id = self.strings.lookup_const_name(id); Opcode::ClsCnsD(id, clsid) } Hhbc::ClsCnsL(_, lid, _) => { let local = self.lookup_local(lid); Opcode::ClsCnsL(local) } Hhbc::Cmp(..) => Opcode::Cmp, Hhbc::CmpOp(_, op, _) => match op { instr::CmpOp::Eq => Opcode::Eq, instr::CmpOp::Gt => Opcode::Gt, instr::CmpOp::Gte => Opcode::Gte, instr::CmpOp::Lt => Opcode::Lt, instr::CmpOp::Lte => Opcode::Lte, instr::CmpOp::NSame => Opcode::NSame, instr::CmpOp::Neq => Opcode::Neq, instr::CmpOp::Same => Opcode::Same, }, Hhbc::ColFromArray(_, kind, _) => Opcode::ColFromArray(kind), Hhbc::CombineAndResolveTypeStruct(ref vids, _) => { Opcode::CombineAndResolveTypeStruct(vids.len() as u32) } Hhbc::Concat(..) => Opcode::Concat, Hhbc::ConcatN(ref vids, _) => Opcode::ConcatN(vids.len() as u32), Hhbc::ConsumeL(lid, _) => { let local = self.lookup_local(lid); Opcode::PushL(local) } Hhbc::ContCheck(kind, _) => Opcode::ContCheck(kind), Hhbc::ContCurrent(_) => Opcode::ContCurrent, Hhbc::ContEnter(..) => Opcode::ContEnter, Hhbc::ContGetReturn(_) => Opcode::ContGetReturn, Hhbc::ContKey(_) => Opcode::ContKey, Hhbc::ContRaise(..) => Opcode::ContRaise, Hhbc::ContValid(_) => Opcode::ContValid, Hhbc::CreateCl { ref operands, clsid, .. } => { let class = self.strings.lookup_class_name(clsid); Opcode::CreateCl(operands.len() as u32, class) } Hhbc::CreateCont(_) => Opcode::CreateCont, Hhbc::CreateSpecialImplicitContext(..) => Opcode::CreateSpecialImplicitContext, Hhbc::Div(..) => Opcode::Div, Hhbc::GetClsRGProp(..) => Opcode::GetClsRGProp, Hhbc::GetMemoKeyL(lid, _) => { let local = self.lookup_local(lid); Opcode::GetMemoKeyL(local) } Hhbc::HasReifiedParent(_, _) => Opcode::HasReifiedParent, Hhbc::Idx(..) => Opcode::Idx, Hhbc::IncDecL(lid, op, _) => { let local = self.lookup_local(lid); Opcode::IncDecL(local, op) } Hhbc::IncDecS(_, op, _) => Opcode::IncDecS(op), Hhbc::IncludeEval(ref ie) => self.emit_include_eval(ie), Hhbc::InitProp(_, prop, op, _) => { let prop = self.strings.lookup_prop_name(prop); Opcode::InitProp(prop, op) } Hhbc::InstanceOfD(_, clsid, _) => { let clsid = self.strings.lookup_class_name(clsid); Opcode::InstanceOfD(clsid) } Hhbc::IsLateBoundCls(_, _) => Opcode::IsLateBoundCls, Hhbc::IsTypeC(_, op, _) => Opcode::IsTypeC(op), Hhbc::IsTypeL(lid, op, _) => { let local = self.lookup_local(lid); Opcode::IsTypeL(local, op) } Hhbc::IsTypeStructC(_, op, _) => Opcode::IsTypeStructC(op), Hhbc::IssetG(_, _) => Opcode::IssetG, Hhbc::IssetL(lid, _) => { let local = self.lookup_local(lid); Opcode::IssetL(local) } Hhbc::IssetS(_, _) => Opcode::IssetS, Hhbc::IterFree(iter_id, _) => Opcode::IterFree(iter_id), Hhbc::LateBoundCls(_) => Opcode::LateBoundCls, Hhbc::LazyClass(clsid, _) => { let clsid = self.strings.lookup_class_name(clsid); Opcode::LazyClass(clsid) } Hhbc::LazyClassFromClass(_, _) => Opcode::LazyClassFromClass, Hhbc::LockObj(..) => Opcode::LockObj, Hhbc::MemoSet(_, ref locals, _) => { let locals = self.convert_local_range(locals); Opcode::MemoSet(locals) } Hhbc::MemoSetEager(_, ref locals, _) => { let locals = self.convert_local_range(locals); Opcode::MemoSetEager(locals) } Hhbc::Modulo(..) => Opcode::Mod, Hhbc::Mul(..) => Opcode::Mul, Hhbc::NewDictArray(hint, _) => Opcode::NewDictArray(hint), Hhbc::NewKeysetArray(ref operands, _) => Opcode::NewKeysetArray(operands.len() as u32), Hhbc::NewObj(_, _) => Opcode::NewObj, Hhbc::NewObjD(clsid, _) => { let clsid = self.strings.lookup_class_name(clsid); Opcode::NewObjD(clsid) } Hhbc::NewObjS(clsref, _) => Opcode::NewObjS(clsref), Hhbc::NewPair(..) => Opcode::NewPair, Hhbc::NewStructDict(ref keys, _, _) => { let keys = Slice::fill_iter( self.strings.alloc, keys.iter().map(|key| self.strings.lookup_ffi_str(*key)), ); Opcode::NewStructDict(keys) } Hhbc::NewVec(ref vids, _) => Opcode::NewVec(vids.len() as u32), Hhbc::Not(..) => Opcode::Not, Hhbc::OODeclExists(_, kind, _) => Opcode::OODeclExists(kind), Hhbc::ParentCls(_) => Opcode::ParentCls, Hhbc::Pow(..) => Opcode::Pow, Hhbc::Print(..) => Opcode::Print, Hhbc::RaiseClassStringConversionWarning(..) => { Opcode::RaiseClassStringConversionWarning } Hhbc::RecordReifiedGeneric(..) => Opcode::RecordReifiedGeneric, Hhbc::ResolveClass(clsid, _) => { let class = self.strings.lookup_class_name(clsid); Opcode::ResolveClass(class) } Hhbc::ResolveClsMethod(_, method, _) => { let method = self.strings.lookup_method_name(method); Opcode::ResolveClsMethod(method) } Hhbc::ResolveClsMethodD(clsid, method, _) => { let class = self.strings.lookup_class_name(clsid); let method = self.strings.lookup_method_name(method); Opcode::ResolveClsMethodD(class, method) } Hhbc::ResolveClsMethodS(clsref, method, _) => { let method = self.strings.lookup_method_name(method); Opcode::ResolveClsMethodS(clsref, method) } Hhbc::ResolveRClsMethod(_, method, _) => { let method = self.strings.lookup_method_name(method); Opcode::ResolveRClsMethod(method) } Hhbc::ResolveRClsMethodS(_, clsref, method, _) => { let method = self.strings.lookup_method_name(method); Opcode::ResolveRClsMethodS(clsref, method) } Hhbc::ResolveFunc(func, _) => { Opcode::ResolveFunc(self.strings.lookup_function_name(func)) } Hhbc::ResolveMethCaller(func, _) => { Opcode::ResolveMethCaller(self.strings.lookup_function_name(func)) } Hhbc::ResolveRClsMethodD(_, clsid, method, _) => { let class = self.strings.lookup_class_name(clsid); let method = self.strings.lookup_method_name(method); Opcode::ResolveRClsMethodD(class, method) } Hhbc::ResolveRFunc(_, func, _) => { Opcode::ResolveRFunc(self.strings.lookup_function_name(func)) } Hhbc::SelfCls(_) => Opcode::SelfCls, Hhbc::SetG(_, _) => Opcode::SetG, Hhbc::SetImplicitContextByValue(..) => Opcode::SetImplicitContextByValue, Hhbc::SetL(_, lid, _) => { let local = self.lookup_local(lid); Opcode::SetL(local) } Hhbc::SetOpL(_, lid, op, _) => { let local = self.lookup_local(lid); Opcode::SetOpL(local, op) } Hhbc::SetOpG(_, op, _) => Opcode::SetOpG(op), Hhbc::SetOpS(_, op, _) => Opcode::SetOpS(op), Hhbc::SetS(_, readonly, _) => Opcode::SetS(readonly), Hhbc::Shl(..) => Opcode::Shl, Hhbc::Shr(..) => Opcode::Shr, Hhbc::Silence(lid, op, _) => { let local = self.lookup_local(lid); Opcode::Silence(local, op) } Hhbc::Sub(..) => Opcode::Sub, Hhbc::This(_) => Opcode::This, Hhbc::ThrowNonExhaustiveSwitch(_) => Opcode::ThrowNonExhaustiveSwitch, Hhbc::UnsetG(_, _) => Opcode::UnsetG, Hhbc::UnsetL(lid, _) => { let local = self.lookup_local(lid); Opcode::UnsetL(local) } Hhbc::VerifyImplicitContextState(_) => Opcode::VerifyImplicitContextState, Hhbc::VerifyOutType(_, pid, _) => { let local = self.lookup_local(pid); Opcode::VerifyOutType(local) } Hhbc::VerifyParamType(_, pid, _) => { let local = self.lookup_local(pid); Opcode::VerifyParamType(local) } Hhbc::VerifyParamTypeTS(_, pid, _) => { let local = self.lookup_local(pid); Opcode::VerifyParamTypeTS(local) } Hhbc::VerifyRetTypeC(..) => Opcode::VerifyRetTypeC, Hhbc::VerifyRetTypeTS(..) => Opcode::VerifyRetTypeTS, Hhbc::WHResult(..) => Opcode::WHResult, Hhbc::Yield(..) => Opcode::Yield, Hhbc::YieldK(..) => Opcode::YieldK, }; self.push_opcode(opcode); } fn emit_instr(&mut self, iid: ir::InstrId, instr: &ir::Instr) { self.emit_loc(instr.loc_id()); trace!( " Instr: {}", ir::print::FmtInstr(self.func, &self.strings.interner, iid) ); use ir::Instr; match instr { Instr::Call(call) => self.emit_call(call), Instr::Hhbc(hhbc) => self.emit_hhbc(hhbc), Instr::MemberOp(op) => self.emit_member_op(op), Instr::Special(special) => self.emit_special(special), Instr::Terminator(terminator) => self.emit_terminator(terminator), } } fn emit_constant(&mut self, cid: ir::ConstantId) { use ir::Constant; let i = if let Some((id, kind)) = self.adata_id_map.get(&cid) { match kind { AdataKind::Dict => Opcode::Dict(*id), AdataKind::Keyset => Opcode::Keyset(*id), AdataKind::Vec => Opcode::Vec(*id), } } else { let lc = self.func.constant(cid); match lc { Constant::Array(_) => unreachable!(), Constant::Bool(false) => Opcode::False, Constant::Bool(true) => Opcode::True, Constant::Dir => Opcode::Dir, Constant::Float(v) => Opcode::Double(*v), Constant::File => Opcode::File, Constant::FuncCred => Opcode::FuncCred, Constant::Int(v) => Opcode::Int(*v), Constant::Method => Opcode::Method, Constant::Named(name) => Opcode::CnsE(*name), Constant::NewCol(k) => Opcode::NewCol(*k), Constant::Null => Opcode::Null, Constant::String(v) => { let s = self.strings.lookup_ffi_str(*v); Opcode::String(s) } Constant::Uninit => Opcode::NullUninit, } }; self.push_opcode(i); } fn emit_loc(&mut self, loc_id: ir::LocId) { if self.loc_id != loc_id { if let Some(loc) = self.func.get_loc(loc_id) { self.loc_id = loc_id; self.instrs .push(Instruct::Pseudo(Pseudo::SrcLoc(hhbc::SrcLoc { line_begin: loc.line_begin, col_begin: loc.col_begin, line_end: loc.line_end, col_end: loc.col_end, }))); } } } fn emit_include_eval(&mut self, ie: &instr::IncludeEval) -> Opcode<'a> { use instr::IncludeKind; match ie.kind { IncludeKind::Eval => Opcode::Eval, IncludeKind::Include => Opcode::Incl, IncludeKind::IncludeOnce => Opcode::InclOnce, IncludeKind::Require => Opcode::Req, IncludeKind::RequireOnce => Opcode::ReqOnce, IncludeKind::RequireOnceDoc => Opcode::ReqDoc, } } /// Emitter for a MemberOp instruction. In IR the MemberOp is a single /// instruction but that maps to multiple HHBC instructions (a BaseOp, zero /// or more Dim Instructs, and a FinalOp). fn emit_member_op(&mut self, op: &instr::MemberOp) { use instr::BaseOp; use instr::FinalOp; let mut stack_index = op.operands.len() as u32; let mut locals = op.locals.iter().copied(); let may_mutate_stack_base = member_op_may_mutate_stack_base(op); match op.base_op { BaseOp::BaseC { mode, .. } => { stack_index -= 1; self.push_opcode(Opcode::BaseC(stack_index, mode)); } BaseOp::BaseGC { mode, .. } => { stack_index -= 1; self.push_opcode(Opcode::BaseGC(stack_index, mode)); } BaseOp::BaseH { .. } => { self.push_opcode(Opcode::BaseH); } BaseOp::BaseL { mode, readonly, .. } => { let lid = locals.next().unwrap(); let local = self.lookup_local(lid); self.push_opcode(Opcode::BaseL(local, mode, readonly)); } BaseOp::BaseSC { mode, readonly, .. } => { stack_index -= 2; self.push_opcode(Opcode::BaseSC(stack_index + 1, stack_index, mode, readonly)); } BaseOp::BaseST { .. } => { todo!("BaseST not allowed in HHBC"); } } for interm_op in op.intermediate_ops.iter() { self.emit_loc(interm_op.loc_id()); let key = self.convert_member_key( &mut stack_index, &mut locals, &interm_op.key, interm_op.readonly, ); self.push_opcode(Opcode::Dim(interm_op.mode, key)); } let num = op.operands.len() as u32 - may_mutate_stack_base as u32; match op.final_op { FinalOp::IncDecM { inc_dec_op, ref key, readonly, loc, .. } => { let key = self.convert_member_key(&mut stack_index, &mut locals, key, readonly); self.emit_loc(loc); self.push_opcode(Opcode::IncDecM(num, inc_dec_op, key)); } FinalOp::QueryM { query_m_op, ref key, readonly, loc, .. } => { let key = self.convert_member_key(&mut stack_index, &mut locals, key, readonly); self.emit_loc(loc); self.push_opcode(Opcode::QueryM(num, query_m_op, key)); } FinalOp::SetM { ref key, readonly, loc, .. } => { let key = self.convert_member_key(&mut stack_index, &mut locals, key, readonly); self.emit_loc(loc); // `data.operands()` includes the stored value but num does not. self.push_opcode(Opcode::SetM(num - 1, key)); // Extra stack slot for the value. stack_index -= 1; } FinalOp::SetOpM { ref key, readonly, set_op_op, loc, .. } => { let key = self.convert_member_key(&mut stack_index, &mut locals, key, readonly); self.emit_loc(loc); // `data.operands()` includes the stored value but num does not. self.push_opcode(Opcode::SetOpM(num - 1, set_op_op, key)); // Extra stack slot for the value. stack_index -= 1; } FinalOp::SetRangeM { sz, set_range_op, loc, .. } => { self.emit_loc(loc); // `data.operands()` includes the params but num does not. self.push_opcode(Opcode::SetRangeM(num - 3, sz, set_range_op)); // Extra stack slot for the values. stack_index -= 3; } FinalOp::UnsetM { ref key, readonly, loc, .. } => { let key = self.convert_member_key(&mut stack_index, &mut locals, key, readonly); self.emit_loc(loc); self.push_opcode(Opcode::UnsetM(num, key)); } } assert_eq!(stack_index as usize, 0); } fn convert_member_key( &mut self, stack_index: &mut u32, locals: &mut impl Iterator<Item = LocalId>, key: &instr::MemberKey, readonly: ir::ReadonlyOp, ) -> hhbc::MemberKey<'a> { match *key { instr::MemberKey::EC => { *stack_index -= 1; hhbc::MemberKey::EC(*stack_index, readonly) } instr::MemberKey::EI(imm) => hhbc::MemberKey::EI(imm, readonly), instr::MemberKey::EL => { let lid = locals.next().unwrap(); let local = self.lookup_local(lid); hhbc::MemberKey::EL(local, readonly) } instr::MemberKey::ET(name) => { let name = self.strings.lookup_ffi_str(name); hhbc::MemberKey::ET(name, readonly) } instr::MemberKey::PC => { *stack_index -= 1; hhbc::MemberKey::PC(*stack_index, readonly) } instr::MemberKey::PL => { let lid = locals.next().unwrap(); let local = self.lookup_local(lid); hhbc::MemberKey::PL(local, readonly) } instr::MemberKey::PT(name) => { let name = self.strings.lookup_prop_name(name); hhbc::MemberKey::PT(name, readonly) } instr::MemberKey::QT(name) => { let name = self.strings.lookup_prop_name(name); hhbc::MemberKey::QT(name, readonly) } instr::MemberKey::W => hhbc::MemberKey::W, } } fn emit_special(&mut self, special: &instr::Special) { use instr::Special; match special { Special::IrToBc(ir_to_bc) => self.emit_ir_to_bc(ir_to_bc), Special::Param => {} Special::Select(..) => { // Select is entirely handled during the push/pop phase. } Special::Copy(_) | Special::Textual(_) | Special::Tmp(..) | Special::Tombstone => { panic!("shouldn't be trying to emit {special:?}") } } } fn emit_ir_to_bc(&mut self, ir_to_bc: &instr::IrToBc) { use ir::FullInstrId; match ir_to_bc { IrToBc::PopC => { self.push_opcode(Opcode::PopC); } IrToBc::PopL(lid) => { let local = self.lookup_local(*lid); self.push_opcode(Opcode::PopL(local)); } IrToBc::PushL(lid) => { let local = self.lookup_local(*lid); self.push_opcode(Opcode::PushL(local)); } IrToBc::PushConstant(vid) => match vid.full() { FullInstrId::Constant(cid) => self.emit_constant(cid), FullInstrId::Instr(_) | FullInstrId::None => panic!("Malformed PushConstant!"), }, IrToBc::PushUninit => self.push_opcode(Opcode::NullUninit), IrToBc::UnsetL(lid) => { let local = self.lookup_local(*lid); self.push_opcode(Opcode::UnsetL(local)); } } } fn emit_terminator(&mut self, terminator: &instr::Terminator) { use instr::Terminator; match *terminator { Terminator::CallAsync(ref call, ref targets) => self.emit_call_async(call, targets), Terminator::Enter(bid, _) => { let label = self.labeler.lookup_or_insert_bid(bid); self.push_opcode(Opcode::Enter(label)); } Terminator::Exit(..) => { self.push_opcode(Opcode::Exit); } Terminator::Fatal(_, op, _) => { self.push_opcode(Opcode::Fatal(op)); } Terminator::IterInit(ref ir_args, _iid) => { let args = hhbc::IterArgs { iter_id: ir_args.iter_id, key_id: ir_args .key_lid() .map_or(hhbc::Local::INVALID, |lid| self.lookup_local(lid)), val_id: self.lookup_local(ir_args.value_lid()), }; let label = self.labeler.lookup_or_insert_bid(ir_args.done_bid()); self.push_opcode(Opcode::IterInit(args, label)); self.jump_to(ir_args.next_bid()); } Terminator::IterNext(ref ir_args) => { let args = hhbc::IterArgs { iter_id: ir_args.iter_id, key_id: ir_args .key_lid() .map_or(hhbc::Local::INVALID, |lid| self.lookup_local(lid)), val_id: self.lookup_local(ir_args.value_lid()), }; let label = self.labeler.lookup_or_insert_bid(ir_args.done_bid()); self.push_opcode(Opcode::IterNext(args, label)); self.jump_to(ir_args.next_bid()); } Terminator::Jmp(bid, _) | Terminator::JmpArgs(bid, _, _) => { let label = self.labeler.lookup_or_insert_bid(bid); self.push_opcode(Opcode::Jmp(label)); } Terminator::JmpOp { cond: _, ref pred, targets, loc: _, } => { use ir::instr::Predicate; let t_label = self.labeler.lookup_or_insert_bid(targets[0]); let i = match pred { Predicate::NonZero => Opcode::JmpNZ(t_label), Predicate::Zero => Opcode::JmpZ(t_label), }; self.push_opcode(i); self.jump_to(targets[1]); } Terminator::MemoGet(ref get) => { let locals = self.convert_local_range(&get.locals); let else_edge = self.labeler.lookup_or_insert_bid(get.no_value_edge()); self.push_opcode(Opcode::MemoGet(else_edge, locals)); self.jump_to(get.value_edge()); } Terminator::MemoGetEager(ref get) => { let locals = self.convert_local_range(&get.locals); let no_value = self.labeler.lookup_or_insert_bid(get.no_value_edge()); let suspended = self.labeler.lookup_or_insert_bid(get.suspended_edge()); self.push_opcode(Opcode::MemoGetEager( [no_value, suspended], Dummy::DEFAULT, locals, )); self.jump_to(get.eager_edge()); } Terminator::NativeImpl(_) => { self.push_opcode(Opcode::NativeImpl); } Terminator::Ret(_, _) => { self.push_opcode(Opcode::RetC); } Terminator::RetCSuspended(_, _) => { self.push_opcode(Opcode::RetCSuspended); } Terminator::RetM(ref vids, _) => { self.push_opcode(Opcode::RetM(vids.len() as u32)); } Terminator::Switch { bounded, base, ref targets, .. } => { let targets = Slice::fill_iter( self.strings.alloc, targets .iter() .copied() .map(|bid| self.labeler.lookup_or_insert_bid(bid)), ); self.push_opcode(Opcode::Switch(bounded, base, targets)); } Terminator::SSwitch { ref cases, ref targets, .. } => { let cases = Slice::fill_iter( self.strings.alloc, cases.iter().map(|case| self.strings.lookup_ffi_str(*case)), ); let targets = Slice::fill_iter( self.strings.alloc, targets .iter() .copied() .map(|bid| self.labeler.lookup_or_insert_bid(bid)), ); self.push_opcode(Opcode::SSwitch { cases, targets, _0: Dummy::DEFAULT, }); } Terminator::Throw(_src, _) => { self.push_opcode(Opcode::Throw); } Terminator::ThrowAsTypeStructException(..) => { self.push_opcode(Opcode::ThrowAsTypeStructException); } Terminator::Unreachable => panic!("shouldn't be trying to emit unreachable"), }; } fn scan_for_run_on_jump(&mut self, bid: BlockId) -> bool { // If the last emitted instr was a jump to this block then it can be elided. if self.instrs.is_empty() { return false; } let mut idx = self.instrs.len(); while idx > 0 { idx -= 1; let instr = self.instrs.get(idx).unwrap(); match *instr { Instruct::Pseudo(Pseudo::TryCatchBegin) => { // We can just fall through a TryCatchBegin. continue; } Instruct::Opcode(Opcode::Enter(label)) | Instruct::Opcode(Opcode::Jmp(label)) => { // The last "interesting" instr was a jump. if let Some(target) = self.labeler.lookup_label(label) { if bid == target { self.instrs.remove(idx); return true; } } } _ => {} } break; } false } fn convert_block(&mut self, bid: BlockId) { let block = self.func.block(bid); trace!( "Block {}{}{}", bid, self.labeler.get_bid(bid).map_or_else(String::new, |i| { let is_dv = false; // FIXME let prefix = if is_dv { "DV" } else { "L" }; format!(" ({}{})", prefix, i.0) }), if block.params.is_empty() { "".to_owned() } else { format!( ", args: [{}]", FmtSep::comma(block.params.iter(), |w, vid| FmtRawVid( ir::ValueId::from_instr(*vid) ) .fmt(w)) ) } ); let run_on = self.scan_for_run_on_jump(bid); // Only emit the label for this block if someone actually calls it. if self.block_entry_edges[&bid] > (run_on as usize) { let label = self.labeler.lookup_or_insert_bid(bid); self.instrs.push(Instruct::Pseudo(Pseudo::Label(label))); } else { trace!(" skipped label (run_on = {run_on})"); } for (iid, instr) in block.iids().map(|iid| (iid, self.func.instr(iid))) { self.emit_instr(iid, instr); } } fn get_next_block(&self, deque: &mut VecDeque<BlockIdOrExFrame>) -> Option<BlockIdOrExFrame> { // If the last bytecode emitted was an unconditional jump (JmpNS) and // its target is an unnamed, unemitted block then prefer that block // next. match self.instrs.last() { Some(&Instruct::Opcode(Opcode::Enter(label))) => { // The last instr WAS a jump. if let Some(bid) = self.labeler.lookup_label(label) { if let Some(idx) = deque.iter().position(|i| i.bid() == bid) { // And we haven't yet emitted it. return deque.remove(idx); } } } _ => {} } deque.pop_front() } fn convert_frame_vec(&mut self, vec: Vec<BlockIdOrExFrame>) { let mut deque: VecDeque<BlockIdOrExFrame> = vec.into(); while let Some(item) = self.get_next_block(&mut deque) { match item { BlockIdOrExFrame::Block(bid) => { self.convert_block(bid); } BlockIdOrExFrame::Frame(frame) => { self.convert_frame(frame); } } } } fn convert_frame(&mut self, frame: ExFrame) { self.instrs.push(Instruct::Pseudo(Pseudo::TryCatchBegin)); self.convert_frame_vec(frame.try_bids); self.instrs.push(Instruct::Pseudo(Pseudo::TryCatchMiddle)); self.convert_frame_vec(frame.catch_bids); self.instrs.push(Instruct::Pseudo(Pseudo::TryCatchEnd)); } } /// Determine if a MemberOp can mutate its Base as a stack entry. This is /// important to know because if it mutates its base then we need to leave the /// base on the stack instead of popping it off when the member_op is finished. fn member_op_may_mutate_stack_base(member_op: &instr::MemberOp) -> bool { use instr::BaseOp; use instr::FinalOp; let write_op = match member_op.final_op { FinalOp::SetRangeM { .. } => true, FinalOp::UnsetM { .. } => true, FinalOp::IncDecM { .. } => true, FinalOp::QueryM { .. } => false, FinalOp::SetM { .. } => true, FinalOp::SetOpM { .. } => true, }; let base_key_is_element_access = member_op.intermediate_ops.get(0).map_or_else( || { member_op .final_op .key() .map_or(true, |k| k.is_element_access()) }, |dim| dim.key.is_element_access(), ); match member_op.base_op { BaseOp::BaseC { .. } => base_key_is_element_access && write_op, BaseOp::BaseGC { .. } | BaseOp::BaseH { .. } | BaseOp::BaseL { .. } | BaseOp::BaseSC { .. } | BaseOp::BaseST { .. } => false, } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/ir_to_bc/ex_frame.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use ir::BlockId; use ir::TryCatchId; /// Collect the Func's Blocks into the tree represented by the exception frames. pub(crate) fn collect_tc_sections(func: &ir::Func<'_>) -> Vec<BlockIdOrExFrame> { let mut root: ExFrame = ExFrame::default(); for bid in func.block_ids() { let tcid = func.block(bid).tcid; let frame = get_frame(&mut root, func, tcid); let bid = BlockIdOrExFrame::Block(bid); frame.push(bid); } root.sort(func); assert!(root.catch_bids.is_empty()); root.try_bids } /// A node or leaf of the exception frame Block tree. #[derive(Debug, PartialEq, Eq)] pub(crate) enum BlockIdOrExFrame { Frame(ExFrame), Block(BlockId), } impl BlockIdOrExFrame { pub(crate) fn bid(&self) -> BlockId { match *self { Self::Block(bid) => bid, Self::Frame(ref frame) => frame.bid(), } } fn frame_mut(&mut self) -> &mut ExFrame { match self { Self::Block(_) => panic!("Not Frame"), Self::Frame(frame) => frame, } } } #[derive(Default, Debug, Eq, PartialEq)] pub(crate) struct ExFrame { exid: ir::ExFrameId, pub try_bids: Vec<BlockIdOrExFrame>, pub catch_bids: Vec<BlockIdOrExFrame>, } impl ExFrame { fn bid(&self) -> BlockId { self.try_bids .first() .or_else(|| self.catch_bids.first()) .map_or(BlockId::NONE, |bof| bof.bid()) } fn sort(&mut self, func: &ir::Func<'_>) { self.try_bids.sort_by(|a, b| Self::sort_fn(func, a, b)); self.catch_bids.sort_by(|a, b| Self::sort_fn(func, a, b)); } fn sort_fn( _func: &ir::Func<'_>, a: &BlockIdOrExFrame, b: &BlockIdOrExFrame, ) -> std::cmp::Ordering { let a_bid = a.bid(); let b_bid = b.bid(); if a_bid == ir::Func::ENTRY_BID || b_bid == ir::Func::ENTRY_BID { return a_bid.cmp(&b_bid); } a_bid.cmp(&b_bid) } } fn find_frame(parent_bids: &[BlockIdOrExFrame], exid: ir::ExFrameId) -> Option<usize> { parent_bids.iter().rposition(|item| { match item { BlockIdOrExFrame::Block(_) => {} BlockIdOrExFrame::Frame(frame) => { if frame.exid == exid { return true; } } } false }) } fn insert_frame<'c>( parent_bids: &'c mut Vec<BlockIdOrExFrame>, exid: ir::ExFrameId, ) -> &'c mut ExFrame { parent_bids.push(BlockIdOrExFrame::Frame(ExFrame { exid, ..Default::default() })); parent_bids.last_mut().unwrap().frame_mut() } fn find_or_insert_frame<'c>( root: &'c mut ExFrame, func: &ir::Func<'_>, exid: ir::ExFrameId, ) -> &'c mut ExFrame { let parent_tcid: TryCatchId = func.ex_frames[&exid].parent; let parent_frame = get_frame(root, func, parent_tcid); if let Some(frame) = find_frame(parent_frame, exid) { parent_frame[frame].frame_mut() } else { insert_frame(parent_frame, exid) } } fn get_frame<'c>( root: &'c mut ExFrame, func: &ir::Func<'_>, tcid: TryCatchId, ) -> &'c mut Vec<BlockIdOrExFrame> { match tcid { TryCatchId::None => &mut root.try_bids, TryCatchId::Try(exid) => { let frame = find_or_insert_frame(root, func, exid); &mut frame.try_bids } TryCatchId::Catch(exid) => { let frame = find_or_insert_frame(root, func, exid); &mut frame.catch_bids } } } #[cfg(test)] mod test { use ir::Block; use ir::BlockId; use ir::TryCatchId; use super::*; fn make_test_func<'a>( blocks: Vec<(/* bid */ usize, /* tcid */ Option<&'static str>)>, ex_frames: Vec<( /* exid */ usize, ( /* parent */ Option<&'static str>, /* catch_bid */ usize, ), )>, ) -> ir::Func<'a> { let mut func = ir::Func::default(); fn conv_tcid(tcid: &str) -> TryCatchId { let exid = ir::ExFrameId::from_usize(tcid[1..].parse().unwrap()); if tcid.starts_with('T') { TryCatchId::Try(exid) } else { TryCatchId::Catch(exid) } } for (bid, tcid) in blocks { let tcid = tcid.map_or(TryCatchId::None, conv_tcid); let block = Block { tcid, ..Block::default() }; assert!(bid == func.blocks.len()); func.blocks.push(block); } for (exid, (parent, catch_bid)) in ex_frames { let exid = ir::ExFrameId::from_usize(exid); let parent = parent.map_or(TryCatchId::None, conv_tcid); let catch_bid = BlockId::from_usize(catch_bid); func.ex_frames .insert(exid, ir::func::ExFrame { parent, catch_bid }); } func } #[test] fn test_collect_tc_section() { let body = make_test_func( vec![ (0, None), (1, None), (2, None), (3, None), (4, None), (5, None), (6, None), (7, Some("T3")), (8, Some("C3")), (9, Some("T2")), (10, Some("T2")), (11, Some("T2")), (12, Some("T2")), (13, Some("C2")), (14, None), (15, None), (16, Some("T1")), (17, Some("T1")), (18, Some("T1")), (19, Some("T1")), (20, Some("C1")), (21, None), (22, None), (23, None), (24, None), (25, None), ], vec![ // ExId, (parent, catch_bid) (1, (None, 20)), (2, (None, 13)), (3, (Some("T2"), 8)), ], ); let root = collect_tc_sections(&body); let expected = vec![ BlockIdOrExFrame::Block(0.into()), BlockIdOrExFrame::Block(1.into()), BlockIdOrExFrame::Block(2.into()), BlockIdOrExFrame::Block(3.into()), BlockIdOrExFrame::Block(4.into()), BlockIdOrExFrame::Block(5.into()), BlockIdOrExFrame::Block(6.into()), BlockIdOrExFrame::Frame(ExFrame { exid: ir::ExFrameId(2), try_bids: vec![ BlockIdOrExFrame::Frame(ExFrame { exid: ir::ExFrameId(3), try_bids: vec![BlockIdOrExFrame::Block(7.into())], catch_bids: vec![BlockIdOrExFrame::Block(8.into())], }), BlockIdOrExFrame::Block(9.into()), BlockIdOrExFrame::Block(10.into()), BlockIdOrExFrame::Block(11.into()), BlockIdOrExFrame::Block(12.into()), ], catch_bids: vec![BlockIdOrExFrame::Block(13.into())], }), BlockIdOrExFrame::Block(14.into()), BlockIdOrExFrame::Block(15.into()), BlockIdOrExFrame::Frame(ExFrame { exid: ir::ExFrameId(1), try_bids: vec![ BlockIdOrExFrame::Block(16.into()), BlockIdOrExFrame::Block(17.into()), BlockIdOrExFrame::Block(18.into()), BlockIdOrExFrame::Block(19.into()), ], catch_bids: vec![BlockIdOrExFrame::Block(20.into())], }), BlockIdOrExFrame::Block(21.into()), BlockIdOrExFrame::Block(22.into()), BlockIdOrExFrame::Block(23.into()), BlockIdOrExFrame::Block(24.into()), BlockIdOrExFrame::Block(25.into()), ]; assert_eq!(root, expected); } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/ir_to_bc/func.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use ffi::Slice; use hhbc::Method; use log::trace; use crate::adata::AdataCache; use crate::convert; use crate::convert::UnitBuilder; use crate::emitter; use crate::pusher; use crate::strings::StringCache; /// Convert an ir::Func to an hhbc::Body. /// /// The conversion has three general phases: push, optimize, and emit. /// /// The push phase runs through the IR graph and inserts artificial pushes and /// pops - before each instruction it pushes that instruction's operands onto /// the stack and after each instruction pops that instruction's returns off the /// stack into unnamed locals (or drops them for dead values). /// /// The optimize phase (currently unimplemented) attempts to optimize the /// instructions by moving common pushes into common locations and eliding /// unnecessary use of locals. /// /// The emit phase then converts the IR by emitting the HHBC sequence itself. /// /// BlockArgs (phi-nodes) are handled like a split instruction - by pushing args /// onto the stack before the jump and popping them off the stack in receiving /// block. /// pub(crate) fn convert_func<'a>( mut func: ir::Func<'a>, strings: &StringCache<'a>, adata: &mut AdataCache<'a>, ) -> hhbc::Body<'a> { // Compute liveness and implicit block parameters. trace!("-------------------- IR"); trace!( "{}", ir::print::DisplayFunc::new(&func, true, &strings.interner) ); trace!("--------------------"); // Start by inserting stack pushes and pops (which are normally not in the // IR) into the IR. trace!("-- compute spills"); func = pusher::run(func, strings); trace!( "-- after pushes:\n{}", ir::print::DisplayFunc::new(&func, true, &strings.interner) ); // Now emit the instructions. trace!("-- emit instrs"); let mut labeler = emitter::Labeler::new(&func); let (body_instrs, decl_vars) = emitter::emit_func(&func, &mut labeler, strings, adata); let return_type_info = crate::types::convert(&func.return_type, strings); let decl_vars = Slice::fill_iter(strings.alloc, decl_vars.into_iter()); let params = Slice::fill_iter( strings.alloc, func.params.into_iter().map(|param| { let name = strings.lookup_ffi_str(param.name); let user_attributes = convert::convert_attributes(param.user_attributes, strings); let default_value = param .default_value .map(|dv| { let label = labeler.lookup_bid(dv.init); hhbc::DefaultValue { label, expr: dv.expr, } }) .into(); hhbc::Param { name, is_variadic: param.is_variadic, is_inout: param.is_inout, is_readonly: param.is_readonly, user_attributes, type_info: crate::types::convert(&param.ty, strings), default_value, } }), ); let doc_comment = func.doc_comment.into(); let upper_bounds = Slice::fill_iter( strings.alloc, func.tparams.iter().map(|(name, tparam)| { let name = strings.lookup_class_name(*name); let bounds = Slice::fill_iter( strings.alloc, tparam .bounds .iter() .map(|ty| crate::types::convert(ty, strings).unwrap()), ); hhbc::UpperBound { name: name.as_ffi_str(), bounds, } }), ); let shadowed_tparams = Slice::fill_iter( strings.alloc, func.shadowed_tparams .iter() .map(|name| strings.lookup_class_name(*name).as_ffi_str()), ); let body_instrs = body_instrs.compact(strings.alloc); let stack_depth = stack_depth::compute_stack_depth(params.as_ref(), body_instrs.as_ref()).unwrap(); hhbc::Body { body_instrs, decl_vars, doc_comment, is_memoize_wrapper: func.is_memoize_wrapper, is_memoize_wrapper_lsb: func.is_memoize_wrapper_lsb, num_iters: func.num_iters, params, return_type_info, shadowed_tparams, upper_bounds, stack_depth, } } pub(crate) fn convert_function<'a>( unit: &mut UnitBuilder<'a>, function: ir::Function<'a>, strings: &StringCache<'a>, ) { trace!( "convert_function {}", function.name.as_bstr(&strings.interner) ); let span = function.func.loc(function.func.loc_id).to_span(); let body = convert_func(function.func, strings, &mut unit.adata_cache); let attributes = convert::convert_attributes(function.attributes, strings); let hhas_func = hhbc::Function { attributes, body, coeffects: convert_coeffects(strings.alloc, &function.coeffects), flags: function.flags, name: strings.lookup_function_name(function.name), span, attrs: function.attrs, }; unit.functions.push(hhas_func); } pub(crate) fn convert_method<'a>( method: ir::Method<'a>, strings: &StringCache<'a>, adata: &mut AdataCache<'a>, ) -> Method<'a> { trace!("convert_method {}", method.name.as_bstr(&strings.interner)); let span = method.func.loc(method.func.loc_id).to_span(); let body = convert_func(method.func, strings, adata); let attributes = convert::convert_attributes(method.attributes, strings); hhbc::Method { attributes, name: strings.lookup_method_name(method.name), body, span, coeffects: convert_coeffects(strings.alloc, &method.coeffects), flags: method.flags, visibility: method.visibility, attrs: method.attrs, } } fn convert_coeffects<'a>( alloc: &'a bumpalo::Bump, coeffects: &ir::Coeffects<'a>, ) -> hhbc::Coeffects<'a> { let static_coeffects = Slice::fill_iter(alloc, coeffects.static_coeffects.iter().copied()); let unenforced_static_coeffects = Slice::fill_iter(alloc, coeffects.unenforced_static_coeffects.iter().copied()); let fun_param = Slice::fill_iter(alloc, coeffects.fun_param.iter().copied()); let cc_param = Slice::fill_iter(alloc, coeffects.cc_param.iter().copied()); let cc_this = Slice::fill_iter( alloc, coeffects.cc_this.iter().map(|inner| hhbc::CcThis { types: Slice::fill_iter(alloc, inner.types.iter().copied()), }), ); let cc_reified = Slice::fill_iter( alloc, coeffects.cc_reified.iter().map(|inner| hhbc::CcReified { is_class: inner.is_class, index: inner.index, types: Slice::fill_iter(alloc, inner.types.iter().copied()), }), ); let closure_parent_scope = coeffects.closure_parent_scope; let generator_this = coeffects.generator_this; let caller = coeffects.caller; hhbc::Coeffects::new( static_coeffects, unenforced_static_coeffects, fun_param, cc_param, cc_this, cc_reified, closure_parent_scope, generator_this, caller, ) }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/ir_to_bc/lib.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. mod adata; mod class; mod constant; mod convert; mod emitter; mod ex_frame; mod func; mod push_count; mod pusher; mod strings; mod types; pub use convert::ir_to_bc;
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/ir_to_bc/pusher.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::sync::Arc; use ir::analysis; use ir::instr; use ir::instr::HasLocals; use ir::instr::HasOperands; use ir::instr::IrToBc; use ir::instr::LocalId; use ir::instr::Special; use ir::instr::Terminator; use ir::passes; use ir::BlockId; use ir::FullInstrId; use ir::Func; use ir::FuncBuilder; use ir::Instr; use ir::InstrId; use ir::InstrIdMap; use ir::LocId; use ir::UnnamedLocalId; use ir::ValueId; use ir::ValueIdMap; use itertools::Itertools; use log::trace; use smallvec::SmallVec; use crate::push_count::PushCount; use crate::strings::StringCache; /// Run through a Func and insert pushes and pops for instructions in /// preparation of emitting bytecode. In general no attempt is made to optimize /// the process - we simply push the needed values before any Instr and pop off /// any stack values after (there is a peephole optimizer that will turn a /// simple pop/push combo into a no-op). /// /// JmpArgs pushes its args and then branches. Block args pop their args at the /// start of a block before executing the block instructions. /// /// In the future we should probably have a pass that attempts to move common /// pushes up to common locations (so if there's a common push in both targets /// of a branch, move the push before the branch). /// pub(crate) fn run<'a>(func: Func<'a>, strings: &StringCache<'a>) -> Func<'a> { let liveness = analysis::LiveInstrs::compute(&func); trace!("LIVENESS: {liveness:?}"); let next_temp_idx = find_next_unnamed_local_idx(&func); trace!("First temporary local is {}", next_temp_idx); let mut pusher = PushInserter { builder: FuncBuilder::with_func(func, Arc::clone(&strings.interner)), liveness, strings, next_temp_idx, instr_ids: Default::default(), }; // Run the blocks in RPO so we see definitions before use. for bid in pusher.builder.func.block_ids() { pusher.run_block(bid); } // Careful! At this point the Func is no longer a valid Func! (For example // we've converted JmpArgs into plain old Jmp). let mut func = pusher.builder.finish(); passes::control::run(&mut func); func } #[derive(Clone, Debug, Default, Eq, PartialEq)] struct BlockInput { stack: Vec<ValueId>, } /// Helper class to compute where we need to insert stack pushes and pops before /// we convert to bytecode. struct PushInserter<'a, 'b> { builder: FuncBuilder<'a>, liveness: analysis::LiveInstrs, strings: &'b StringCache<'a>, next_temp_idx: usize, instr_ids: InstrIdMap<ir::LocalId>, } impl<'a, 'b> PushInserter<'a, 'b> { fn alloc_temp(&mut self, iid: InstrId) -> ir::LocalId { let temp = ir::LocalId::Unnamed(UnnamedLocalId::from_usize(self.next_temp_idx)); self.next_temp_idx += 1; self.instr_ids.insert(iid, temp); temp } fn lookup_temp(&self, iid: InstrId) -> ir::LocalId { *self.instr_ids.get(&iid).unwrap() } fn consume_temp(&self, iid: InstrId) -> Option<ir::LocalId> { // TODO: Consider marking the temp for reuse (but then we have to think // about liveness across blocks). self.instr_ids.get(&iid).copied() } fn run_block(&mut self, bid: BlockId) { self.builder.start_block(bid); trace!("BLOCK {bid}"); let block = self.builder.func.block_mut(bid); let params = std::mem::take(&mut block.params); let mut instrs = std::mem::take(&mut block.iids); let terminator = instrs.pop().unwrap(); trace!( " dead on entry: [{}]", self.liveness.blocks[bid] .dead_on_entry .iter() .map(|iid| format!("%{}", iid.as_usize())) .join(", ") ); let dead_on_entry = self.liveness.blocks[bid].dead_on_entry.clone(); for &iid in &dead_on_entry { // This iid is dead on entry to the block - we need to unset it. if let Some(lid) = self.consume_temp(iid) { trace!(" UNSET {}", ir::print::FmtLid(lid, &self.strings.interner)); self.builder .emit(Instr::Special(Special::IrToBc(IrToBc::UnsetL(lid)))); } } for iid in params.into_iter().rev() { trace!(" PARAM {}", iid,); if dead_on_entry.contains(&iid) { // The result of this Param is immediately dead. self.builder .emit(Instr::Special(Special::IrToBc(IrToBc::PopC))); } else { let lid = self.alloc_temp(iid); self.builder .emit(Instr::Special(Special::IrToBc(IrToBc::PopL(lid)))); } } for iid in instrs { self.run_instr(iid); } self.run_terminator(terminator); } fn run_instr(&mut self, iid: InstrId) { trace!( " INSTR {}: {}", iid, ir::print::FmtInstr(&self.builder.func, &self.strings.interner, iid) ); let instr = self.builder.func.instr(iid); // Handle weird instructions match instr { Instr::Special(Special::Select(..)) => return self.run_select(iid), Instr::Terminator(_) => unreachable!(), _ => {} } // Push needed items onto the stack. let is_param = instr.is_param(); let push_count = instr.push_count(); self.push_operands(iid); // Push instr if !is_param { let bid = self.builder.cur_bid(); self.builder.func.block_mut(bid).iids.push(iid); } // Pop/Transfer items off the stack. self.instr_cleanup(iid, push_count); } fn instr_cleanup(&mut self, iid: InstrId, push_count: usize) { if push_count == 0 { // no-op } else if push_count == 1 { if self.liveness.instr_last_use[iid].contains(&iid) { // The result of this Instr is immediately dead. self.builder .emit(Instr::Special(Special::IrToBc(IrToBc::PopC))); } else { let lid = self.alloc_temp(iid); self.builder .emit(Instr::Special(Special::IrToBc(IrToBc::PopL(lid)))); } } else { // This is guaranteed to be followed by 'select' statements - which // will pop their values as necessary. } } fn run_select(&mut self, iid: InstrId) { // Select is weird - it just represents a stack slot from a previous // instruction. self.instr_cleanup(iid, 1); } fn run_terminator(&mut self, iid: InstrId) { // Deal with the terminator. Although the inputs are the same as normal // instructions the outputs are handled differently. trace!( " TERMINATOR {}: {}", iid, ir::print::FmtInstr(&self.builder.func, &self.strings.interner, iid) ); self.push_operands(iid); let bid = self.builder.cur_bid(); let instr = self.builder.func.instr(iid); match *instr { // terminals Instr::Terminator(Terminator::JmpArgs(target, _, loc)) => { // The args have already been pushed as operands. // Convert the JmpArgs into a Jmp *self.builder.func.instr_mut(iid) = Instr::Terminator(Terminator::Jmp(target, loc)); } Instr::Terminator(_) => { // No special handling. } // non-terminals _ => unreachable!(), } self.builder.func.block_mut(bid).iids.push(iid); } fn push_vids(&mut self, cur_iid: InstrId, vids: &[ValueId]) { // For each ValueId we need to know if this is the last use of the value // or not. If it's the last use then we need to teleport it from the // Local to the stack (PushL) - otherwise we copy it (CGetL). We also // need to be careful about declaring last use when it's possible for a // ValueId to be used multiple times in the same call. // For each vid that is consumed by this Instr figure out the last index // that uses it. let mut vid_histogram: ValueIdMap<usize> = vids .iter() .copied() .filter(|vid| { vid.instr().map_or(false, |iid| { self.liveness.instr_last_use[iid].contains(&cur_iid) }) }) .sorted_by_key(|vid| vid.raw()) .dedup_with_count() .map(|(count, vid)| (vid, count)) .collect(); for vid in vids { let vid_consume = vid_histogram.get_mut(vid).map_or(false, |count| { *count -= 1; *count == 0 }); self.push_input(*vid, vid_consume); } } fn push_input(&mut self, vid: ValueId, vid_consume: bool) { match vid.full() { FullInstrId::None => { unreachable!(); } FullInstrId::Instr(iid) => { if vid_consume { // This instr consumes this value. let lid = self.consume_temp(iid).unwrap(); // Peephole: If the previous instr was a PopL(lid) then // we just elide the pair. if let Some(iid) = self.builder.cur_block().iids.last() { match self.builder.func.instr(*iid) { Instr::Special(Special::IrToBc(IrToBc::PopL(popl))) if *popl == lid => { self.builder.cur_block_mut().iids.pop(); return; } _ => {} } } self.builder .emit(Instr::Special(Special::IrToBc(IrToBc::PushL(lid)))); } else { // This instr does NOT consume the value. let lid = self.lookup_temp(iid); self.builder .emit(Instr::Hhbc(instr::Hhbc::CGetL(lid, LocId::NONE))); } } FullInstrId::Constant(cid) => { self.builder .emit(Instr::Special(Special::IrToBc(IrToBc::PushConstant( ValueId::from_constant(cid), )))); } } } fn push_operands(&mut self, iid: InstrId) { let instr = self.builder.func.instr(iid); match *instr { Instr::Call(..) | Instr::Terminator(Terminator::CallAsync(..)) => { self.push_call_operands(iid) } _ => { let operands = SmallVec::<[ValueId; 4]>::from_slice(instr.operands()); self.push_vids(iid, &operands); } } } fn push_call_operands(&mut self, iid: InstrId) { let instr = self.builder.func.instr(iid); let call = match instr { Instr::Call(call) | Instr::Terminator(Terminator::CallAsync(call, _)) => call, _ => unreachable!(), }; let num_inouts = call.inouts.as_ref().map_or(0, |inouts| inouts.len()); let has_class = match &call.detail { ir::instr::CallDetail::FCallClsMethod { .. } | ir::instr::CallDetail::FCallClsMethodD { .. } | ir::instr::CallDetail::FCallClsMethodM { .. } | ir::instr::CallDetail::FCallClsMethodS { .. } | ir::instr::CallDetail::FCallClsMethodSD { .. } | ir::instr::CallDetail::FCallFuncD { .. } | ir::instr::CallDetail::FCallFunc => false, ir::instr::CallDetail::FCallCtor | ir::instr::CallDetail::FCallObjMethod { .. } | ir::instr::CallDetail::FCallObjMethodD { .. } => true, }; // Need to copy the operands so we can write to the mutable // self.builder. let operands = SmallVec::<[ValueId; 4]>::from_slice(instr.operands()); for _ in 0..num_inouts { self.builder .emit(Instr::Special(Special::IrToBc(IrToBc::PushUninit))); } if !has_class { self.builder .emit(Instr::Special(Special::IrToBc(IrToBc::PushUninit))); } else { self.push_vids(iid, &operands[0..1]); } self.builder .emit(Instr::Special(Special::IrToBc(IrToBc::PushUninit))); self.push_vids(iid, &operands[has_class as usize..]); } } fn find_next_unnamed_local_idx(func: &Func<'_>) -> usize { let mut next_unnamed_local_idx: usize = 0; for instr in func.body_instrs() { if let Some(idx) = instr .locals() .iter() .filter_map(|lid| match lid { LocalId::Named(_) => None, LocalId::Unnamed(idx) => Some(idx.as_usize()), }) .max() { next_unnamed_local_idx = usize::max(next_unnamed_local_idx, idx + 1); } } next_unnamed_local_idx }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/ir_to_bc/push_count.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use ir::instr; use ir::instr::IrToBc; use ir::instr::Special; use ir::Instr; pub(crate) trait PushCount<'a> { /// How many values are pushed onto the stack? fn push_count(&self) -> usize; } impl<'a> PushCount<'a> for Instr { fn push_count(&self) -> usize { match self { // We shouldn't be asking for push count on some types. Instr::Special(Special::Tmp(_)) | Instr::Terminator(_) => unreachable!(), // Other types are complex and have to compute their push count // themselves. Instr::Call(call) => call.num_rets as usize, Instr::Hhbc(hhbc) => hhbc.push_count(), Instr::MemberOp(op) => op.num_values(), // --- 0 pushed values Instr::Special( Special::Copy(_) | Special::Textual(_) | Special::IrToBc( IrToBc::PopC | IrToBc::PopL(_) | IrToBc::PushL(_) | IrToBc::PushConstant(..) | IrToBc::PushUninit | IrToBc::UnsetL(_), ) | Special::Select(..) | Special::Tombstone, ) => 0, // --- 1 pushed value Instr::Special(Special::Param) => 1, } } } impl<'a> PushCount<'a> for instr::Hhbc { fn push_count(&self) -> usize { use instr::Hhbc; match self { // --- 0 pushed values Hhbc::CheckClsReifiedGenericMismatch(..) | Hhbc::CheckClsRGSoft(..) | Hhbc::CheckThis(_) | Hhbc::ContCheck(..) | Hhbc::InitProp(..) | Hhbc::IterFree(..) | Hhbc::RaiseClassStringConversionWarning(..) | Hhbc::Silence(..) | Hhbc::ThrowNonExhaustiveSwitch(_) | Hhbc::UnsetG(..) | Hhbc::UnsetL(..) | Hhbc::VerifyImplicitContextState(_) | Hhbc::VerifyParamTypeTS(..) => 0, // --- 1 pushed value Hhbc::AKExists(..) | Hhbc::Add(..) | Hhbc::AddElemC(..) | Hhbc::AddNewElemC(..) | Hhbc::ArrayIdx(..) | Hhbc::ArrayMarkLegacy(..) | Hhbc::ArrayUnmarkLegacy(..) | Hhbc::Await(..) | Hhbc::AwaitAll(..) | Hhbc::BareThis(..) | Hhbc::BitAnd(..) | Hhbc::BitNot(..) | Hhbc::BitOr(..) | Hhbc::BitXor(..) | Hhbc::CGetG(..) | Hhbc::CGetL(..) | Hhbc::CGetQuietL(..) | Hhbc::CGetS(..) | Hhbc::CUGetL(..) | Hhbc::CastBool(..) | Hhbc::CastDict(..) | Hhbc::CastDouble(..) | Hhbc::CastInt(..) | Hhbc::CastKeyset(..) | Hhbc::CastString(..) | Hhbc::CastVec(..) | Hhbc::ChainFaults(..) | Hhbc::CheckProp(..) | Hhbc::ClassGetC(..) | Hhbc::ClassHasReifiedGenerics(..) | Hhbc::ClassName(..) | Hhbc::Clone(..) | Hhbc::ClsCns(..) | Hhbc::ClsCnsD(..) | Hhbc::ClsCnsL(..) | Hhbc::Cmp(..) | Hhbc::CmpOp(..) | Hhbc::ColFromArray(..) | Hhbc::CombineAndResolveTypeStruct(..) | Hhbc::Concat(..) | Hhbc::ConcatN(..) | Hhbc::ConsumeL(..) | Hhbc::ContCurrent(_) | Hhbc::ContEnter(..) | Hhbc::ContGetReturn(_) | Hhbc::ContKey(_) | Hhbc::ContRaise(..) | Hhbc::ContValid(_) | Hhbc::CreateCl { .. } | Hhbc::CreateCont(..) | Hhbc::CreateSpecialImplicitContext(..) | Hhbc::Div(..) | Hhbc::GetClsRGProp(..) | Hhbc::GetMemoKeyL(..) | Hhbc::HasReifiedParent(..) | Hhbc::Idx(..) | Hhbc::IncDecL(..) | Hhbc::IncDecS(..) | Hhbc::IncludeEval(_) | Hhbc::InstanceOfD(..) | Hhbc::IsLateBoundCls(..) | Hhbc::IsTypeC(..) | Hhbc::IsTypeL(..) | Hhbc::IsTypeStructC(..) | Hhbc::IssetG(..) | Hhbc::IssetL(..) | Hhbc::IssetS(..) | Hhbc::LateBoundCls(_) | Hhbc::LazyClass(..) | Hhbc::LazyClassFromClass(..) | Hhbc::LockObj { .. } | Hhbc::MemoSet(..) | Hhbc::MemoSetEager(..) | Hhbc::Modulo(..) | Hhbc::Mul(..) | Hhbc::NewDictArray(..) | Hhbc::NewKeysetArray(..) | Hhbc::NewObj(..) | Hhbc::NewObjD(..) | Hhbc::NewObjS(..) | Hhbc::NewPair(..) | Hhbc::NewStructDict(..) | Hhbc::NewVec(..) | Hhbc::Not(..) | Hhbc::OODeclExists(..) | Hhbc::ParentCls(_) | Hhbc::Pow(..) | Hhbc::Print(..) | Hhbc::RecordReifiedGeneric(..) | Hhbc::ResolveClass(..) | Hhbc::ResolveClsMethod(..) | Hhbc::ResolveClsMethodD(..) | Hhbc::ResolveClsMethodS(..) | Hhbc::ResolveFunc(..) | Hhbc::ResolveMethCaller(..) | Hhbc::ResolveRClsMethod(..) | Hhbc::ResolveRClsMethodD(..) | Hhbc::ResolveRClsMethodS(..) | Hhbc::ResolveRFunc(..) | Hhbc::SelfCls(_) | Hhbc::SetG(..) | Hhbc::SetImplicitContextByValue(..) | Hhbc::SetL(..) | Hhbc::SetOpG(..) | Hhbc::SetOpL(..) | Hhbc::SetOpS(..) | Hhbc::SetS(..) | Hhbc::Shl(..) | Hhbc::Shr(..) | Hhbc::Sub(..) | Hhbc::This(_) | Hhbc::VerifyOutType(..) | Hhbc::VerifyParamType(..) | Hhbc::VerifyRetTypeC(..) | Hhbc::VerifyRetTypeTS(..) | Hhbc::WHResult(..) | Hhbc::Yield(..) | Hhbc::YieldK(..) => 1, // --- 2 pushed values Hhbc::ClassGetTS(..) => 2, } } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/ir_to_bc/strings.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::sync::Arc; use dashmap::DashMap; use ffi::Str; use ir::StringInterner; use ir::UnitBytesId; pub(crate) struct StringCache<'a> { pub alloc: &'a bumpalo::Bump, cache: DashMap<UnitBytesId, Str<'a>>, pub interner: Arc<StringInterner>, } impl<'a> StringCache<'a> { pub fn new(alloc: &'a bumpalo::Bump, interner: Arc<StringInterner>) -> Self { let cache = DashMap::with_capacity(interner.len()); Self { alloc, cache, interner, } } pub fn lookup_ffi_str(&self, id: UnitBytesId) -> Str<'a> { *self.cache.entry(id).or_insert_with(|| { let s = self.interner.lookup_bstr(id); Str::new_slice(self.alloc, &s) }) } pub fn lookup_class_name(&self, id: ir::ClassId) -> hhbc::ClassName<'a> { let s = self.lookup_ffi_str(id.id); hhbc::ClassName::new(s) } pub fn lookup_const_name(&self, id: ir::ConstId) -> hhbc::ConstName<'a> { let s = self.lookup_ffi_str(id.id); hhbc::ConstName::new(s) } pub fn lookup_method_name(&self, id: ir::MethodId) -> hhbc::MethodName<'a> { let s = self.lookup_ffi_str(id.id); hhbc::MethodName::new(s) } pub fn lookup_function_name(&self, id: ir::FunctionId) -> hhbc::FunctionName<'a> { let s = self.lookup_ffi_str(id.id); hhbc::FunctionName::new(s) } pub fn lookup_prop_name(&self, id: ir::PropId) -> hhbc::PropName<'a> { let s = self.lookup_ffi_str(id.id); hhbc::PropName::new(s) } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/ir_to_bc/types.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use ffi::Maybe; use ffi::Str; use hhbc::Constraint; use hhbc::TypeInfo; use ir::BaseType; use ir::TypeConstraintFlags; use crate::strings::StringCache; fn convert_type<'a>(ty: &ir::TypeInfo, strings: &StringCache<'a>) -> TypeInfo<'a> { let mut user_type = ty.user_type.map(|ut| strings.lookup_ffi_str(ut)); let name = if let Some(name) = base_type_string(&ty.enforced.ty) { if user_type.is_none() { let nullable = ty .enforced .modifiers .contains(TypeConstraintFlags::Nullable); let soft = ty.enforced.modifiers.contains(TypeConstraintFlags::Soft); user_type = Some(if !nullable && !soft { name } else { let len = name.len() + nullable as usize + soft as usize; let p = strings.alloc.alloc_slice_fill_copy(len, 0u8); let mut i = 0; if soft { p[i] = b'@'; i += 1; } if nullable { p[i] = b'?'; i += 1; } p[i..].copy_from_slice(&name); ffi::Slice::new(p) }); } Some(name) } else { match ty.enforced.ty { BaseType::Mixed | BaseType::Void => None, BaseType::Class(name) => Some(strings.lookup_ffi_str(name.id)), _ => unreachable!(), } }; TypeInfo { user_type: user_type.into(), type_constraint: Constraint { name: name.map(|name| Str::new_slice(strings.alloc, &name)).into(), flags: ty.enforced.modifiers, }, } } fn convert_types<'a>( tis: &[ir::TypeInfo], strings: &StringCache<'a>, ) -> ffi::Slice<'a, TypeInfo<'a>> { ffi::Slice::fill_iter( strings.alloc, tis.iter().map(|ti| convert_type(ti, strings)), ) } fn base_type_string(ty: &ir::BaseType) -> Option<Str<'static>> { match ty { BaseType::Class(_) | BaseType::Mixed | BaseType::Void => None, BaseType::None => Some(Str::new("".as_bytes())), BaseType::AnyArray => Some(ir::types::BUILTIN_NAME_ANY_ARRAY), BaseType::Arraykey => Some(ir::types::BUILTIN_NAME_ARRAYKEY), BaseType::Bool => Some(ir::types::BUILTIN_NAME_BOOL), BaseType::Classname => Some(ir::types::BUILTIN_NAME_CLASSNAME), BaseType::Darray => Some(ir::types::BUILTIN_NAME_DARRAY), BaseType::Dict => Some(ir::types::BUILTIN_NAME_DICT), BaseType::Float => Some(ir::types::BUILTIN_NAME_FLOAT), BaseType::Int => Some(ir::types::BUILTIN_NAME_INT), BaseType::Keyset => Some(ir::types::BUILTIN_NAME_KEYSET), BaseType::Nonnull => Some(ir::types::BUILTIN_NAME_NONNULL), BaseType::Noreturn => Some(ir::types::BUILTIN_NAME_NORETURN), BaseType::Nothing => Some(ir::types::BUILTIN_NAME_NOTHING), BaseType::Null => Some(ir::types::BUILTIN_NAME_NULL), BaseType::Num => Some(ir::types::BUILTIN_NAME_NUM), BaseType::Resource => Some(ir::types::BUILTIN_NAME_RESOURCE), BaseType::String => Some(ir::types::BUILTIN_NAME_STRING), BaseType::This => Some(ir::types::BUILTIN_NAME_THIS), BaseType::Typename => Some(ir::types::BUILTIN_NAME_TYPENAME), BaseType::Varray => Some(ir::types::BUILTIN_NAME_VARRAY), BaseType::VarrayOrDarray => Some(ir::types::BUILTIN_NAME_VARRAY_OR_DARRAY), BaseType::Vec => Some(ir::types::BUILTIN_NAME_VEC), BaseType::VecOrDict => Some(ir::types::BUILTIN_NAME_VEC_OR_DICT), } } pub(crate) fn convert<'a>(ty: &ir::TypeInfo, strings: &StringCache<'a>) -> Maybe<TypeInfo<'a>> { if ty.is_empty() { Maybe::Nothing } else { Maybe::Just(convert_type(ty, strings)) } } pub(crate) fn convert_typedef<'a>(td: ir::Typedef, strings: &StringCache<'a>) -> hhbc::Typedef<'a> { let ir::Typedef { name, attributes, type_info_union, type_structure, loc, attrs, case_type, } = td; let name = strings.lookup_class_name(name); let span = hhbc::Span { line_begin: loc.line_begin, line_end: loc.line_end, }; let attributes = crate::convert::convert_attributes(attributes, strings); let type_info_union = convert_types(type_info_union.as_ref(), strings); let type_structure = crate::convert::convert_typed_value(&type_structure, strings); hhbc::Typedef { name, attributes, type_info_union, type_structure, span, attrs, case_type, } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/textual/class.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. //! To support late static binding classes are set up as a two tier system - //! every class has a singleton "static class" which holds its static members. //! //! `(new C())->a` refers to the property "a" of an instance of "C". //! `C::$a` refers to the property "$a" of the static class for "C". //! //! To get the static class singleton call `load_static_class`. use std::sync::Arc; use anyhow::Error; use hash::IndexMap; use itertools::Itertools; use log::trace; use naming_special_names_rust::special_idents; use super::func; use super::textual; use crate::func::FuncInfo; use crate::func::MethodInfo; use crate::mangle::FunctionName; use crate::mangle::Intrinsic; use crate::mangle::Mangle; use crate::mangle::TypeName; use crate::state::UnitState; use crate::textual::FieldAttribute; use crate::textual::TextualFile; use crate::types::convert_ty; type Result<T = (), E = Error> = std::result::Result<T, E>; /// Classes are defined as: /// /// type NAME = [ properties*; ] /// pub(crate) fn write_class( txf: &mut TextualFile<'_>, unit_state: &mut UnitState, class: ir::Class<'_>, ) -> Result { trace!("Convert Class {}", class.name.as_bstr(&unit_state.strings)); let class = crate::lower::lower_class(class, Arc::clone(&unit_state.strings)); let mut state = ClassState::new(txf, unit_state, class); state.write_class() } #[derive(Copy, Clone, Eq, PartialEq)] pub(crate) enum IsStatic { Static, NonStatic, } impl IsStatic { pub(crate) fn as_bool(&self) -> bool { matches!(self, IsStatic::Static) } pub(crate) fn as_attr(self) -> ir::Attr { match self { IsStatic::NonStatic => ir::Attr::AttrNone, IsStatic::Static => ir::Attr::AttrStatic, } } } struct ClassState<'a, 'b, 'c> { class: ir::Class<'c>, needs_factory: bool, txf: &'a mut TextualFile<'b>, unit_state: &'a mut UnitState, } impl<'a, 'b, 'c> ClassState<'a, 'b, 'c> { fn new( txf: &'a mut TextualFile<'b>, unit_state: &'a mut UnitState, class: ir::Class<'c>, ) -> Self { let needs_factory = !class.flags.is_interface() && !class.flags.is_trait() && !class.flags.is_enum() && !class.flags.contains(ir::Attr::AttrIsClosureClass); ClassState { class, needs_factory, txf, unit_state, } } } impl ClassState<'_, '_, '_> { fn write_class(&mut self) -> Result { self.write_type(IsStatic::Static)?; self.write_type(IsStatic::NonStatic)?; // Note: Class constants turn into static properties. if self.needs_factory { self.write_factory()?; } let methods = std::mem::take(&mut self.class.methods); for method in methods { self.write_method(method)?; } Ok(()) } /// Write the type for a (class, is_static) with the properties of the class. fn write_type(&mut self, is_static: IsStatic) -> Result { let mut metadata: IndexMap<&str, textual::Const> = IndexMap::default(); let kind = if self.class.flags.is_interface() { "interface" } else if self.class.flags.is_trait() { "trait" } else { "class" }; metadata.insert("kind", kind.into()); metadata.insert("static", is_static.as_bool().into()); // Traits say they're final - because they're not "real" classes. But that // will be strange for us since we treat them as bases. if !self.class.flags.is_trait() && !self.class.flags.is_interface() { metadata.insert("final", self.class.flags.is_final().into()); } let mut fields: Vec<textual::Field<'_>> = Vec::new(); let properties = std::mem::take(&mut self.class.properties); for prop in &properties { if prop.flags.is_static() == is_static.as_bool() { self.write_property(&mut fields, prop)?; } } self.class.properties = properties; let mut extends: Vec<ir::ClassId> = Vec::new(); if let Some(base) = compute_base(&self.class) { extends.push(base); } extends.extend(self.class.implements.iter()); extends.extend(self.class.uses.iter()); let extends = extends .into_iter() .map(|id| TypeName::class(id, is_static)) .collect_vec(); let cname = TypeName::class(self.class.name, is_static); self.txf.define_type( &cname, Some(&self.class.src_loc), extends.iter(), fields.into_iter(), metadata.iter().map(|(k, v)| (*k, v)), )?; Ok(()) } fn write_property( &mut self, fields: &mut Vec<textual::Field<'_>>, prop: &ir::Property<'_>, ) -> Result { let ir::Property { name, mut flags, ref attributes, visibility: _, initial_value: _, ref type_info, doc_comment: _, } = *prop; flags.clear(ir::Attr::AttrStatic); let name = name.mangle(&self.unit_state.strings); let visibility = if flags.is_private() { textual::Visibility::Private } else if flags.is_protected() { textual::Visibility::Protected } else { textual::Visibility::Public }; flags.clear(ir::Attr::AttrForbidDynamicProps); flags.clear(ir::Attr::AttrPrivate); flags.clear(ir::Attr::AttrProtected); flags.clear(ir::Attr::AttrPublic); flags.clear(ir::Attr::AttrSystemInitialValue); flags.clear(ir::Attr::AttrInterceptable); let mut tx_attributes = Vec::new(); let comments = Vec::new(); if !flags.is_empty() { textual_todo! { message = ("CLASS FLAGS: {:?}", flags), self.txf.write_comment(&format!("TODO: class flags: {flags:?}"))? }; } for attribute in attributes { // We don't do anything with class attributes. They don't affect // normal program flow - but can be seen by reflection so it's // questionable if we need them for analysis. let name = TypeName::Class(attribute.name); if attribute.arguments.is_empty() { tx_attributes.push(FieldAttribute::Unparameterized { name }); } else { let mut parameters = Vec::new(); for arg in &attribute.arguments { textual_todo! { parameters.push(format!("TODO: {arg:?}")); } } tx_attributes.push(FieldAttribute::Parameterized { name, parameters }); } } let ty = convert_ty(&type_info.enforced, &self.unit_state.strings); fields.push(textual::Field { name: name.into(), ty: ty.into(), visibility, attributes: tx_attributes, comments, }); Ok(()) } /// Build the factory for a class. /// /// The factory only allocates an object of the required type. The initialization is done via a separate constructor invocation on the allocated object. /// /// The factory method is used only when the class of an object to allocate is not known statically. Otherwise, we directly use Textual's typed allocation builtin. fn write_factory(&mut self) -> Result { let name = FunctionName::Intrinsic(Intrinsic::Factory(self.class.name)); let static_ty = static_ty(self.class.name); let ty = non_static_ty(self.class.name); let params = vec![textual::Param { name: special_idents::THIS.into(), attr: None, ty: static_ty.into(), }]; let attributes = textual::FuncAttributes::default(); self.txf.define_function( &name, Some(&self.class.src_loc), &attributes, &params, &ty, &[], |fb| { let obj = fb.write_expr_stmt(textual::Expr::Alloc(ty.deref()))?; fb.ret(obj)?; Ok(()) }, ) } fn write_method(&mut self, method: ir::Method<'_>) -> Result { trace!( "Convert Method {}::{}", self.class.name.as_bstr(&self.unit_state.strings), method.name.as_bstr(&self.unit_state.strings) ); let is_static = match method.attrs.is_static() { true => IsStatic::Static, false => IsStatic::NonStatic, }; let this_ty = class_ty(self.class.name, is_static); let func_info = FuncInfo::Method(MethodInfo { name: method.name, attrs: method.attrs, class: &self.class, is_static, flags: method.flags, }); if method.attrs.is_abstract() { func::write_func_decl( self.txf, self.unit_state, this_ty, method.func, Arc::new(func_info), )?; } else { func::lower_and_write_func(self.txf, self.unit_state, this_ty, method.func, func_info)?; } Ok(()) } } /// For a given class return the Ty for its non-static (instance) type. pub(crate) fn non_static_ty(class: ir::ClassId) -> textual::Ty { let cname = TypeName::Class(class); textual::Ty::Ptr(Box::new(textual::Ty::Type(cname))) } /// For a given class return the Ty for its static type. pub(crate) fn static_ty(class: ir::ClassId) -> textual::Ty { let cname = TypeName::StaticClass(class); textual::Ty::Ptr(Box::new(textual::Ty::Type(cname))) } pub(crate) fn class_ty(class: ir::ClassId, is_static: IsStatic) -> textual::Ty { match is_static { IsStatic::Static => static_ty(class), IsStatic::NonStatic => non_static_ty(class), } } fn compute_base(class: &ir::Class<'_>) -> Option<ir::ClassId> { if class.flags.is_trait() { // Traits express bases through a 'require extends'. let req = class .requirements .iter() .find(|r| r.kind == ir::TraitReqKind::MustExtend); req.map(|req| req.name) } else { class.base } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/textual/decls.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use anyhow::Error; use hash::HashSet; use crate::hack::Builtin; use crate::hack::Hhbc; use crate::textual::TextualFile; type Result<T = (), E = Error> = std::result::Result<T, E>; /// This is emitted with every SIL file to declare the "standard" definitions /// that we use. pub(crate) fn write_decls(txf: &mut TextualFile<'_>, subset: &HashSet<Builtin>) -> Result<()> { txf.write_comment("----- BUILTIN DECLS STARTS HERE -----")?; Builtin::write_decls(txf, subset)?; let hhbc_subset = subset .iter() .filter_map(|builtin| match builtin { Builtin::Hhbc(hhbc) => Some(*hhbc), _ => None, }) .collect(); Hhbc::write_decls(txf, &hhbc_subset)?; txf.debug_separator()?; Ok(()) }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/textual/func.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::collections::HashSet; use std::sync::Arc; use anyhow::Error; use ir::instr::HasLoc; use ir::instr::HasLocals; use ir::instr::Hhbc; use ir::instr::Predicate; use ir::instr::Special; use ir::instr::Terminator; use ir::instr::Textual; use ir::BlockId; use ir::ClassId; use ir::Constant; use ir::Func; use ir::FunctionFlags; use ir::FunctionId; use ir::IncDecOp; use ir::Instr; use ir::InstrId; use ir::LocId; use ir::LocalId; use ir::MethodFlags; use ir::MethodId; use ir::SpecialClsRef; use ir::StringInterner; use ir::ValueId; use itertools::Itertools; use log::trace; use naming_special_names_rust::special_idents; use crate::class; use crate::class::IsStatic; use crate::hack; use crate::lower; use crate::mangle::FunctionName; use crate::mangle::GlobalName; use crate::mangle::Intrinsic; use crate::mangle::TypeName; use crate::member_op; use crate::state::UnitState; use crate::textual; use crate::textual::Expr; use crate::textual::Sid; use crate::textual::TextualFile; use crate::typed_value; use crate::types::convert_ty; use crate::util; type Result<T = (), E = Error> = std::result::Result<T, E>; /// Functions are defined as taking a param bundle. /// /// f(params: HackParams): mixed; pub(crate) fn write_function( txf: &mut TextualFile<'_>, state: &mut UnitState, function: ir::Function<'_>, ) -> Result { trace!("Convert Function {}", function.name.as_bstr(&state.strings)); let func_info = FuncInfo::Function(FunctionInfo { name: function.name, attrs: function.attrs, flags: function.flags, }); lower_and_write_func(txf, state, textual::Ty::VoidPtr, function.func, func_info) } pub(crate) fn compute_func_params<'a, 'b>( params: &Vec<ir::Param<'_>>, unit_state: &'a mut UnitState, this_ty: textual::Ty, ) -> Result<Vec<(textual::Param<'b>, LocalId)>> { let mut result = Vec::new(); // Prepend the 'this' parameter. let this_param = textual::Param { name: special_idents::THIS.into(), attr: None, ty: this_ty.into(), }; let this_lid = LocalId::Named(unit_state.strings.intern_str(special_idents::THIS)); result.push((this_param, this_lid)); for p in params { let name_bytes = unit_state.strings.lookup_bytes(p.name); let name = util::escaped_string(&name_bytes); let mut attr = Vec::new(); if p.is_variadic { attr.push(textual::VARIADIC); } let param = textual::Param { name: name.to_string().into(), attr: Some(attr.into_boxed_slice()), ty: convert_ty(&p.ty.enforced, &unit_state.strings).into(), }; let lid = LocalId::Named(p.name); result.push((param, lid)); } Ok(result) } pub(crate) fn lower_and_write_func( txf: &mut TextualFile<'_>, unit_state: &mut UnitState, this_ty: textual::Ty, func: ir::Func<'_>, func_info: FuncInfo<'_>, ) -> Result { fn lower_and_write_func_( txf: &mut TextualFile<'_>, unit_state: &mut UnitState, this_ty: textual::Ty, func: ir::Func<'_>, mut func_info: FuncInfo<'_>, ) -> Result { let func = lower::lower_func(func, &mut func_info, Arc::clone(&unit_state.strings)); ir::verify::verify_func(&func, &Default::default(), &unit_state.strings); write_func(txf, unit_state, this_ty, func, Arc::new(func_info)) } let has_defaults = func.params.iter().any(|p| p.default_value.is_some()); if has_defaults { // When a function has defaults we need to split it into multiple // functions which each take a different number of parameters, // initialize them and then forward on to the function that takes all // the parameters. let inits = split_default_func(&func, &func_info, &unit_state.strings); for init in inits { lower_and_write_func_(txf, unit_state, this_ty.clone(), init, func_info.clone())?; } } lower_and_write_func_(txf, unit_state, this_ty, func, func_info) } /// Given a Func that has default parameters make a version of the function with /// those parameters stripped out (one version is returned with each successive /// parameter removed). fn split_default_func<'a>( orig_func: &Func<'a>, func_info: &FuncInfo<'_>, strings: &StringInterner, ) -> Vec<Func<'a>> { let mut result = Vec::new(); let loc = orig_func.loc_id; let min_params = orig_func .params .iter() .take_while(|p| p.default_value.is_none()) .count(); let max_params = orig_func.params.len(); for param_count in min_params..max_params { let mut func = orig_func.clone(); let target_bid = func.params[param_count].default_value.unwrap().init; func.params.truncate(param_count); for i in min_params..param_count { func.params[i].default_value = None; } // replace the entrypoint with a jump to the initializer. let iid = func.alloc_instr(Instr::Terminator(ir::instr::Terminator::Jmp( target_bid, loc, ))); func.block_mut(Func::ENTRY_BID).iids = vec![iid]; // And turn the 'enter' calls into a tail call into the non-default // function. let exit_bid = { let mut block = ir::Block::default(); let params = orig_func .params .iter() .map(|param| { let instr = Instr::Hhbc(Hhbc::CGetL(LocalId::Named(param.name), loc)); let iid = func.alloc_instr(instr); block.iids.push(iid); ValueId::from(iid) }) .collect_vec(); let instr = match func_info { FuncInfo::Function(fi) => Instr::simple_call(fi.name, &params, loc), FuncInfo::Method(mi) => { let this_str = strings.intern_str(special_idents::THIS); let instr = Instr::Hhbc(Hhbc::CGetL(LocalId::Named(this_str), loc)); let receiver = func.alloc_instr(instr); block.iids.push(receiver); Instr::simple_method_call(mi.name, receiver.into(), &params, loc) } }; let iid = func.alloc_instr(instr); block.iids.push(iid); let iid = func.alloc_instr(Instr::ret(iid.into(), loc)); block.iids.push(iid); func.alloc_bid(block) }; for instr in func.instrs.iter_mut() { match instr { Instr::Terminator(Terminator::Enter(bid, _)) => *bid = exit_bid, _ => {} } } result.push(func); } result } fn write_func( txf: &mut TextualFile<'_>, unit_state: &mut UnitState, this_ty: textual::Ty, mut func: ir::Func<'_>, func_info: Arc<FuncInfo<'_>>, ) -> Result { let strings = Arc::clone(&unit_state.strings); let params = std::mem::take(&mut func.params); let (tx_params, param_lids): (Vec<_>, Vec<_>) = compute_func_params(&params, unit_state, this_ty)? .into_iter() .unzip(); let ret_ty = convert_ty(&func.return_type.enforced, &strings); let lids = func .body_instrs() .flat_map(HasLocals::locals) .cloned() .collect::<HashSet<_>>(); // TODO(arr): figure out how to provide more precise types let local_ty = textual::Ty::VoidPtr; let locals = lids .into_iter() .filter(|lid| !param_lids.contains(lid)) .sorted_by(|x, y| cmp_lid(&strings, x, y)) .zip(std::iter::repeat(&local_ty)) .collect::<Vec<_>>(); let name = match *func_info { FuncInfo::Method(ref mi) => match mi.name { name if name.is_86cinit(&strings) => { FunctionName::Intrinsic(Intrinsic::ConstInit(mi.class.name)) } name if name.is_86pinit(&strings) => { FunctionName::Intrinsic(Intrinsic::PropInit(mi.class.name)) } name if name.is_86sinit(&strings) => { FunctionName::Intrinsic(Intrinsic::StaticInit(mi.class.name)) } _ => FunctionName::method(mi.class.name, mi.is_static, mi.name), }, FuncInfo::Function(ref fi) => FunctionName::Function(fi.name), }; let span = func.loc(func.loc_id).clone(); let attributes = textual::FuncAttributes { is_async: func_info.is_async(), is_curry: false, is_final: func_info.attrs().is_final(), }; txf.define_function( &name, Some(&span), &attributes, &tx_params, &ret_ty, &locals, { let func_info = Arc::clone(&func_info); |fb| { let mut func = rewrite_jmp_ops(func); ir::passes::clean::run(&mut func); let mut state = FuncState::new(fb, Arc::clone(&strings), &func, func_info); for bid in func.block_ids() { write_block(&mut state, bid)?; } Ok(()) } }, )?; // For a user static method also generate an instance stub which forwards to // the static method. match (&*func_info, name) { ( FuncInfo::Method( mi @ MethodInfo { is_static: IsStatic::Static, .. }, ), FunctionName::Method(..) | FunctionName::Unmangled(..), ) => { write_instance_stub(txf, unit_state, mi, &tx_params, &ret_ty, &span)?; } _ => {} } Ok(()) } pub(crate) fn write_func_decl( txf: &mut TextualFile<'_>, unit_state: &mut UnitState, this_ty: textual::Ty, mut func: ir::Func<'_>, func_info: Arc<FuncInfo<'_>>, ) -> Result { let params = std::mem::take(&mut func.params); let param_tys = compute_func_params(&params, unit_state, this_ty)? .into_iter() .map(|(param, _)| textual::Ty::clone(&param.ty)) .collect_vec(); let ret_ty = convert_ty(&func.return_type.enforced, &unit_state.strings); let name = match *func_info { FuncInfo::Method(ref mi) => match mi.name { name if name.is_86cinit(&unit_state.strings) => { FunctionName::Intrinsic(Intrinsic::ConstInit(mi.class.name)) } name if name.is_86pinit(&unit_state.strings) => { FunctionName::Intrinsic(Intrinsic::PropInit(mi.class.name)) } name if name.is_86sinit(&unit_state.strings) => { FunctionName::Intrinsic(Intrinsic::StaticInit(mi.class.name)) } _ => FunctionName::method(mi.class.name, mi.is_static, mi.name), }, FuncInfo::Function(ref fi) => FunctionName::Function(fi.name), }; let attributes = textual::FuncAttributes { is_async: func_info.is_async(), is_final: func_info.attrs().is_final(), is_curry: false, }; txf.declare_function(&name, &attributes, &param_tys, &ret_ty)?; Ok(()) } /// For each static method we also write a non-static version of the method so /// that callers of 'self::foo()' don't have to know if foo is static or /// non-static. fn write_instance_stub( txf: &mut TextualFile<'_>, unit_state: &mut UnitState, method_info: &MethodInfo<'_>, tx_params: &[textual::Param<'_>], ret_ty: &textual::Ty, span: &ir::SrcLoc, ) -> Result { let strings = &unit_state.strings; let name_str = FunctionName::method( method_info.class.name, IsStatic::NonStatic, method_info.name, ); let attributes = textual::FuncAttributes::default(); let mut tx_params = tx_params.to_vec(); let inst_ty = method_info.non_static_ty(); tx_params[0].ty = (&inst_ty).into(); let locals = Vec::default(); txf.define_function( &name_str, Some(span), &attributes, &tx_params, ret_ty, &locals, |fb| { fb.comment("forward to the static method")?; let this_str = strings.intern_str(special_idents::THIS); let this_lid = LocalId::Named(this_str); let this = fb.load(&inst_ty, textual::Expr::deref(this_lid))?; let static_this = hack::call_builtin(fb, hack::Builtin::GetStaticClass, [this])?; let target = FunctionName::method(method_info.class.name, IsStatic::Static, method_info.name); let params: Vec<Sid> = std::iter::once(Ok(static_this)) .chain(tx_params.iter().skip(1).map(|param| { let lid = LocalId::Named(strings.intern_str(param.name.as_ref())); fb.load(&param.ty, textual::Expr::deref(lid)) })) .try_collect()?; let call = fb.call(&target, params)?; fb.ret(call)?; Ok(()) }, )?; Ok(()) } fn write_block(state: &mut FuncState<'_, '_, '_>, bid: BlockId) -> Result { trace!(" Block {bid}"); let block = state.func.block(bid); let params = block .params .iter() .map(|iid| state.alloc_sid_for_iid(*iid)) .collect_vec(); // The entry BID is always included for us. if bid != Func::ENTRY_BID { state.fb.write_label(bid, &params)?; } // All the non-terminators. let n_iids = block.iids.len() - 1; for iid in &block.iids[..n_iids] { write_instr(state, *iid)?; } // The terminator. write_terminator(state, block.terminator_iid())?; // Exception handler. let handler = state.func.catch_target(bid); if handler != BlockId::NONE { state.fb.write_exception_handler(handler)?; } Ok(()) } fn write_instr(state: &mut FuncState<'_, '_, '_>, iid: InstrId) -> Result { let instr = state.func.instr(iid); trace!(" Instr {iid}: {instr:?}"); state.update_loc(instr.loc_id())?; // In general don't write directly to `w` here - isolate the formatting to // the `textual` crate. match *instr { Instr::Call(ref call) => write_call(state, iid, call)?, Instr::Hhbc(Hhbc::CreateCl { ref operands, clsid, loc: _, }) => { let ty = class::non_static_ty(clsid).deref(); let cons = FunctionName::Intrinsic(Intrinsic::Construct(clsid)); let obj = state.fb.write_expr_stmt(textual::Expr::Alloc(ty))?; let operands = operands .iter() .map(|vid| state.lookup_vid(*vid)) .collect_vec(); state.fb.call_static(&cons, obj.into(), operands)?; state.set_iid(iid, obj); } Instr::Hhbc( Hhbc::CGetL(lid, _) | Hhbc::CGetQuietL(lid, _) | Hhbc::CUGetL(lid, _) | Hhbc::ConsumeL(lid, _), ) => write_load_var(state, iid, lid)?, Instr::Hhbc(Hhbc::CGetS([field, class], _, _)) => { let class_id = lookup_constant_string(state.func, class).map(ClassId::new); let field_str = lookup_constant_string(state.func, field); let output = if let Some(field_str) = field_str { let field = util::escaped_string(&state.strings.lookup_bstr(field_str)); let this = match class_id { None => { // "C"::foo state.lookup_vid(class) } Some(cid) => { // C::foo // This isn't created by HackC but can be created by infer // lowering. state.load_static_class(cid)?.into() } }; state.call_builtin(hack::Builtin::FieldGet, (this, field))? } else { // Although the rest of these are technically valid they're // basically impossible to produce with HackC. panic!("Unhandled CGetS"); }; state.set_iid(iid, output); } Instr::Hhbc(Hhbc::SetS([field, class, value], _, _)) => { // Note that "easy" SetS are lowered before this point. let class_str = lookup_constant_string(state.func, class); let field_str = lookup_constant_string(state.func, field); let value = state.lookup_vid(value); match (class_str, field_str) { (None, Some(f)) => { // $x::foo let obj = state.lookup_vid(class); let field = util::escaped_string(&state.strings.lookup_bstr(f)); state.store_mixed( Expr::field(obj, textual::Ty::unknown(), field), value.clone(), )?; } // Although the rest of these are technically valid they're // basically impossible to produce with HackC. _ => { panic!("Unhandled SetS"); } } state.set_iid(iid, value); } Instr::Hhbc(Hhbc::IncDecL(lid, op, _)) => write_inc_dec_l(state, iid, lid, op)?, Instr::Hhbc(Hhbc::NewObjD(clsid, _)) => { // NewObjD allocates a default initialized object; constructor invocation is a // *separate* instruction. Thus we can translate it directly as textual Alloc // instruction. let ty = class::non_static_ty(clsid).deref(); let obj = state.fb.write_expr_stmt(Expr::Alloc(ty))?; // HHVM calls 86pinit via NewObjD (and friends) when necessary. We // can't be sure so just call it explicitly. state.fb.call_static( &FunctionName::Intrinsic(Intrinsic::PropInit(clsid)), obj.into(), (), )?; state.set_iid(iid, obj); } Instr::Hhbc(Hhbc::InstanceOfD(target, cid, _)) => { let ty = class::non_static_ty(cid).deref(); let target = Box::new(state.lookup_vid(target)); // The result of __sil_instanceof is unboxed int, but we need a boxed HackBool let output = state.call_builtin(hack::Builtin::Bool, [Expr::InstanceOf(target, ty)])?; state.set_iid(iid, output); } Instr::Hhbc(Hhbc::ResolveClass(cid, _)) => { let vid = state.load_static_class(cid)?; state.set_iid(iid, vid); } Instr::Hhbc(Hhbc::ResolveClsMethodD(cid, method, _)) => { let that = state.load_static_class(cid)?; let name = FunctionName::Method(TypeName::StaticClass(cid), method); let expr = state.fb.write_alloc_curry(name, Some(that.into()), ())?; state.set_iid(iid, expr); } Instr::Hhbc(Hhbc::ResolveFunc(func_id, _)) => { let name = FunctionName::Function(func_id); let expr = state.fb.write_alloc_curry(name, None, ())?; state.set_iid(iid, expr); } Instr::Hhbc(Hhbc::ResolveMethCaller(func_id, _)) => { // ResolveMethCaller is weird in that HackC builds a function which // calls the method. let name = FunctionName::Function(func_id); let that = textual::Expr::null(); let expr = state.fb.write_alloc_curry(name, None, [that])?; state.set_iid(iid, expr); } Instr::Hhbc(Hhbc::SelfCls(_)) => { let method_info = state .func_info .expect_method("SelfCls used in non-method context"); let cid = method_info.class.name; let vid = state.load_static_class(cid)?; state.set_iid(iid, vid); } Instr::Hhbc(Hhbc::SetL(vid, lid, _)) => { write_set_var(state, lid, vid)?; // SetL emits the input as the output. state.copy_iid(iid, vid); } Instr::Hhbc(Hhbc::This(_)) => write_load_this(state, iid)?, Instr::Hhbc(Hhbc::UnsetL(lid, _)) => { state.store_mixed( textual::Expr::deref(lid), textual::Expr::Const(textual::Const::Null), )?; } Instr::MemberOp(ref mop) => member_op::write(state, iid, mop)?, Instr::Special(Special::Textual(Textual::AssertFalse(vid, _))) => { // I think "prune_not" means "stop if this expression IS true"... let pred = hack::expr_builtin(hack::Builtin::IsTrue, [state.lookup_vid(vid)]); state.fb.prune_not(pred)?; } Instr::Special(Special::Textual(Textual::AssertTrue(vid, _))) => { // I think "prune" means "stop if this expression IS NOT true"... let pred = hack::expr_builtin(hack::Builtin::IsTrue, [state.lookup_vid(vid)]); state.fb.prune(pred)?; } Instr::Special(Special::Textual(Textual::Deref(..))) => { // Do nothing - the expectation is that this will be emitted as a // Expr inlined in the target instruction (from lookup_iid()). } Instr::Special(Special::Textual(Textual::HackBuiltin { ref target, ref values, loc: _, })) => write_builtin(state, iid, target, values)?, Instr::Special(Special::Textual(Textual::LoadGlobal { id, is_const })) => { let name = match is_const { false => GlobalName::Global(id), true => GlobalName::GlobalConst(id), }; let var = textual::Var::global(name); let expr = state.load_mixed(textual::Expr::deref(var))?; state.set_iid(iid, expr); } Instr::Special(Special::Textual(Textual::String(s))) => { let expr = { let s = state.strings.lookup_bstr(s); let s = util::escaped_string(&s); let s = hack::expr_builtin(hack::Builtin::String, [s]); state.fb.write_expr_stmt(s)? }; state.set_iid(iid, expr); } Instr::Special(Special::Copy(vid)) => { write_copy(state, iid, vid)?; } Instr::Special(Special::IrToBc(..)) => todo!(), Instr::Special(Special::Param) => todo!(), Instr::Special(Special::Select(vid, _idx)) => { textual_todo! { let vid = state.lookup_vid(vid); let expr = state.fb.write_expr_stmt(vid)?; state.set_iid(iid, expr); } } Instr::Special(Special::Tmp(..)) => todo!(), Instr::Special(Special::Tombstone) => todo!(), Instr::Hhbc(ref hhbc) => { // This should only handle instructions that can't be rewritten into // a simpler form (like control flow and generic calls). Everything // else should be handled in lower(). textual_todo! { message = ("Non-lowered hhbc instr: {hhbc:?} (from {})", ir::print::formatters::FmtFullLoc(state.func.loc(hhbc.loc_id()), &state.strings)), use ir::instr::HasOperands; let name = FunctionName::Unmangled(format!("TODO_hhbc_{}", hhbc)); let operands = instr .operands() .iter() .map(|vid| state.lookup_vid(*vid)) .collect_vec(); let output = state.fb.call(&name,operands)?; state.set_iid(iid, output); } } Instr::Terminator(_) => unreachable!(), } Ok(()) } fn write_copy(state: &mut FuncState<'_, '_, '_>, iid: InstrId, vid: ValueId) -> Result { use hack::Builtin; use textual::Const; use typed_value::typed_value_expr; match vid.full() { ir::FullInstrId::Constant(cid) => { let constant = state.func.constant(cid); let expr = match constant { Constant::Array(tv) => typed_value_expr(tv, &state.strings), Constant::Bool(false) => Expr::Const(Const::False), Constant::Bool(true) => Expr::Const(Const::True), Constant::Dir => todo!(), Constant::File => todo!(), Constant::Float(f) => Expr::Const(Const::Float(*f)), Constant::FuncCred => todo!(), Constant::Int(i) => hack::expr_builtin(Builtin::Int, [Expr::Const(Const::Int(*i))]), Constant::Method => todo!(), Constant::Named(..) => todo!(), Constant::NewCol(..) => todo!(), Constant::Null => Expr::Const(Const::Null), Constant::String(s) => { let s = util::escaped_string(&state.strings.lookup_bytes(*s)); hack::expr_builtin(Builtin::String, [Expr::Const(Const::String(s))]) } Constant::Uninit => Expr::Const(Const::Null), }; let expr = state.fb.write_expr_stmt(expr)?; state.set_iid(iid, expr); } ir::FullInstrId::Instr(instr) => state.copy_iid(iid, ValueId::from_instr(instr)), ir::FullInstrId::None => unreachable!(), } Ok(()) } fn write_terminator(state: &mut FuncState<'_, '_, '_>, iid: InstrId) -> Result { let terminator = match state.func.instr(iid) { Instr::Terminator(terminator) => terminator, _ => unreachable!(), }; trace!(" Instr {iid}: {terminator:?}"); state.update_loc(terminator.loc_id())?; match *terminator { Terminator::Enter(bid, _) | Terminator::Jmp(bid, _) => { state.fb.jmp(&[bid], ())?; } Terminator::Exit(msg, _) => { let msg = state.lookup_vid(msg); state.call_builtin(hack::Builtin::Hhbc(hack::Hhbc::Exit), [msg])?; state.fb.unreachable()?; } Terminator::Fatal(msg, _, _) => { let msg = state.lookup_vid(msg); state.call_builtin(hack::Builtin::Hhbc(hack::Hhbc::Fatal), [msg])?; state.fb.unreachable()?; } Terminator::JmpArgs(bid, ref params, _) => { let params = params.iter().map(|v| state.lookup_vid(*v)).collect_vec(); state.fb.jmp(&[bid], params)?; } Terminator::JmpOp { cond: _, pred: _, targets: [true_bid, false_bid], loc: _, } => { // We just need to emit the jmp - the rewrite_jmp_ops() pass should // have already inserted assert in place on the target bids. state.fb.jmp(&[true_bid, false_bid], ())?; } Terminator::MemoGet(..) | Terminator::MemoGetEager(..) => { // This should have been lowered. unreachable!(); } Terminator::Ret(vid, _) => { let sid = state.lookup_vid(vid); state.fb.ret(sid)?; } Terminator::Unreachable => { state.fb.unreachable()?; } Terminator::CallAsync(..) | Terminator::IterInit(..) | Terminator::IterNext(..) | Terminator::NativeImpl(..) | Terminator::RetCSuspended(..) | Terminator::RetM(..) | Terminator::SSwitch { .. } | Terminator::Switch { .. } | Terminator::ThrowAsTypeStructException { .. } => { state.write_todo(&format!("{}", terminator))?; state.fb.unreachable()?; } Terminator::Throw(vid, _) => { textual_todo! { let expr = state.lookup_vid(vid); let target = FunctionName::Unmangled("TODO_throw".to_string()); state.fb.call(&target, [expr])?; state.fb.unreachable()?; } } } Ok(()) } fn write_builtin( state: &mut FuncState<'_, '_, '_>, iid: InstrId, target: &str, values: &[ValueId], ) -> Result { let params = values .iter() .map(|vid| state.lookup_vid(*vid)) .collect_vec(); let target = FunctionName::Unmangled(target.to_string()); let output = state.fb.call(&target, params)?; state.set_iid(iid, output); Ok(()) } fn write_load_this(state: &mut FuncState<'_, '_, '_>, iid: InstrId) -> Result { let sid = state.load_this()?; state.set_iid(iid, sid); Ok(()) } fn write_load_var(state: &mut FuncState<'_, '_, '_>, iid: InstrId, lid: LocalId) -> Result { let sid = state.load_mixed(textual::Expr::deref(lid))?; state.set_iid(iid, sid); Ok(()) } fn write_set_var(state: &mut FuncState<'_, '_, '_>, lid: LocalId, vid: ValueId) -> Result { let value = state.lookup_vid(vid); state.store_mixed(textual::Expr::deref(lid), value) } fn write_call(state: &mut FuncState<'_, '_, '_>, iid: InstrId, call: &ir::Call) -> Result { use ir::instr::CallDetail; use ir::FCallArgsFlags; let ir::Call { ref operands, context, ref detail, flags, num_rets, ref inouts, ref readonly, loc: _, } = *call; let in_trait = state.func_info.declared_in_trait(); if !inouts.as_ref().map_or(true, |inouts| inouts.is_empty()) { textual_todo! { state.fb.comment("TODO: inouts")?; } } assert!(readonly.as_ref().map_or(true, |ro| ro.is_empty())); if num_rets >= 2 { textual_todo! { state.fb.comment("TODO: num_rets >= 2")?; } } // flags &= FCallArgsFlags::LockWhileUnwinding - ignored let is_async = flags & FCallArgsFlags::HasAsyncEagerOffset != 0; let args = detail.args(operands); let mut args = args .iter() .copied() .map(|vid| state.lookup_vid(vid)) .collect_vec(); // A 'splat' is a call with an expanded array: // foo(1, 2, ...$a) let mut splat = None; if flags & FCallArgsFlags::HasUnpack != 0 { // 'unpack' means that the last arg was a splat. splat = args.pop(); } if flags & FCallArgsFlags::HasGenerics != 0 { textual_todo! { state.fb.comment("TODO: FCallArgsFlags::HasGenerics")?; } } if flags & FCallArgsFlags::SkipRepack != 0 { textual_todo! { state.fb.comment("TODO: FCallArgsFlags::SkipRepack")?; } } if flags & FCallArgsFlags::SkipCoeffectsCheck != 0 { textual_todo! { state.fb.comment("TODO: FCallArgsFlags::SkipCoeffectsCheck")?; } } if flags & FCallArgsFlags::EnforceMutableReturn != 0 { // todo!(); } if flags & FCallArgsFlags::EnforceReadonlyThis != 0 { textual_todo! { state.fb.comment("TODO: FCallArgsFlags::EnforceReadonlyThis")?; } } if flags & FCallArgsFlags::ExplicitContext != 0 { if let Some(context) = state.strings.lookup_bytes_or_none(context) { // For analysis context shouldn't really matter. For now with a // calling context just report it as a comment. let context = util::escaped_string(&context); state.fb.comment(&format!("ExplicitContext: {context}"))?; } } if flags & FCallArgsFlags::HasInOut != 0 { textual_todo! { state.fb.comment("TODO: FCallArgsFlags::HasInOut")?; } } if flags & FCallArgsFlags::EnforceInOut != 0 { textual_todo! { state.fb.comment("TODO: FCallArgsFlags::EnforceInOut")?; } } if flags & FCallArgsFlags::EnforceReadonly != 0 { textual_todo! { state.fb.comment("TODO: FCallArgsFlags::EnforceReadonly")?; } } if flags & FCallArgsFlags::NumArgsStart != 0 { textual_todo! { state.fb.comment("TODO: FCallArgsFlags::NumArgsStart")?; } } if let Some(splat) = splat { // For a splat we'll pass the splat through a function that the model // can recognize so it understands that it needs some extra analysis. let splat = hack::call_builtin(state.fb, hack::Builtin::SilSplat, [splat])?; args.push(splat.into()); } let mut output = match *detail { CallDetail::FCallClsMethod { .. } => write_todo(state.fb, "FCallClsMethod")?, CallDetail::FCallClsMethodD { clsid, method } => { // C::foo() let target = FunctionName::method(clsid, IsStatic::Static, method); let this = state.load_static_class(clsid)?; state.fb.call_static(&target, this.into(), args)? } CallDetail::FCallClsMethodM { method, log: _ } => { // $c::foo() // TODO: figure out better typing. If this is coming from a // `classname` parameter we at least have a lower-bound. let target = FunctionName::untyped_method(method); let obj = state.lookup_vid(detail.class(operands)); state.fb.call_virtual(&target, obj, args)? } CallDetail::FCallClsMethodS { .. } => state.write_todo("TODO_FCallClsMethodS")?, CallDetail::FCallClsMethodSD { clsref, method } => match clsref { SpecialClsRef::SelfCls => { // self::foo() - Static call to the method in the current class. let mi = state.expect_method_info(); let is_static = mi.is_static; let target = if in_trait { let base = ClassId::from_str("__self__", &state.strings); FunctionName::method(base, is_static, method) } else { FunctionName::method(mi.class.name, is_static, method) }; let this = state.load_this()?; state.fb.call_static(&target, this.into(), args)? } SpecialClsRef::LateBoundCls => { // static::foo() - Virtual call to the method in the current class. let mi = state.expect_method_info(); let target = FunctionName::method(mi.class.name, mi.is_static, method); let this = state.load_this()?; state.fb.call_virtual(&target, this.into(), args)? } SpecialClsRef::ParentCls => { // parent::foo() - Static call to the method in the parent class. let mi = state.expect_method_info(); let is_static = mi.is_static; let target = if in_trait { let base = ClassId::from_str("__parent__", &state.strings); FunctionName::method(base, is_static, method) } else { let base = if let Some(base) = mi.class.base { base } else { // Uh oh. We're asking to call parent::foo() when we don't // have a known parent. This can happen in a trait... ClassId::from_str("__parent__", &state.strings) }; FunctionName::method(base, is_static, method) }; let this = state.load_this()?; state.fb.call_static(&target, this.into(), args)? } _ => unreachable!(), }, CallDetail::FCallCtor => unreachable!(), CallDetail::FCallFunc => { // $foo() let target = detail.target(operands); let target = state.lookup_vid(target); let name = FunctionName::Intrinsic(Intrinsic::Invoke(TypeName::Unknown)); state.fb.call_virtual(&name, target, args)? } CallDetail::FCallFuncD { func } => { // foo() let target = FunctionName::Function(func); // A top-level function is called like a class static in a special // top-level class. Its 'this' pointer is null. state.fb.call_static(&target, textual::Expr::null(), args)? } CallDetail::FCallObjMethod { .. } => state.write_todo("FCallObjMethod")?, CallDetail::FCallObjMethodD { flavor, method } => { // $x->y() // This should have been handled in lowering. assert!(flavor != ir::ObjMethodOp::NullSafe); // TODO: need to try to figure out the type. let target = FunctionName::untyped_method(method); let obj = state.lookup_vid(detail.obj(operands)); state.fb.call_virtual(&target, obj, args)? } }; if is_async { output = state.call_builtin(hack::Builtin::Hhbc(hack::Hhbc::Await), [output])?; } state.set_iid(iid, output); Ok(()) } fn write_inc_dec_l( state: &mut FuncState<'_, '_, '_>, iid: InstrId, lid: LocalId, op: IncDecOp, ) -> Result { let builtin = match op { IncDecOp::PreInc => hack::Hhbc::Add, IncDecOp::PostInc => hack::Hhbc::Add, IncDecOp::PreDec => hack::Hhbc::Sub, IncDecOp::PostDec => hack::Hhbc::Sub, _ => unreachable!(), }; let pre = state.load_mixed(textual::Expr::deref(lid))?; let one = state.call_builtin(hack::Builtin::Int, [1])?; let post = state.call_builtin(hack::Builtin::Hhbc(builtin), (pre, one))?; state.store_mixed(textual::Expr::deref(lid), post)?; let sid = match op { IncDecOp::PreInc | IncDecOp::PreDec => pre, IncDecOp::PostInc | IncDecOp::PostDec => post, _ => unreachable!(), }; state.set_iid(iid, sid); Ok(()) } pub(crate) struct FuncState<'a, 'b, 'c> { pub(crate) fb: &'a mut textual::FuncBuilder<'b, 'c>, pub(crate) func: &'a ir::Func<'a>, iid_mapping: ir::InstrIdMap<textual::Expr>, func_info: Arc<FuncInfo<'a>>, pub(crate) strings: Arc<StringInterner>, } impl<'a, 'b, 'c> FuncState<'a, 'b, 'c> { fn new( fb: &'a mut textual::FuncBuilder<'b, 'c>, strings: Arc<StringInterner>, func: &'a ir::Func<'a>, func_info: Arc<FuncInfo<'a>>, ) -> Self { Self { fb, func, iid_mapping: Default::default(), func_info, strings, } } pub fn alloc_sid_for_iid(&mut self, iid: InstrId) -> Sid { let sid = self.fb.alloc_sid(); self.set_iid(iid, sid); sid } pub(crate) fn call_builtin( &mut self, target: hack::Builtin, params: impl textual::VarArgs, ) -> Result<Sid> { hack::call_builtin(self.fb, target, params) } pub(crate) fn copy_iid(&mut self, iid: InstrId, input: ValueId) { let expr = self.lookup_vid(input); self.set_iid(iid, expr); } fn expect_method_info(&self) -> &MethodInfo<'_> { self.func_info.expect_method("not in class context") } /// Loads the static singleton for a class. fn load_static_class(&mut self, cid: ClassId) -> Result<textual::Sid> { match *self.func_info { FuncInfo::Method(MethodInfo { class, is_static, .. }) if class.name == cid => { // If we're already in a member of the class then use '$this'. match is_static { IsStatic::Static => self.load_this(), IsStatic::NonStatic => { let this = self.load_this()?; hack::call_builtin(self.fb, hack::Builtin::GetStaticClass, [this]) } } } _ => { let cname = TypeName::Class(cid); let ty = textual::Ty::Type(cname); self.fb.lazy_class_initialize(&ty) } } } pub(crate) fn load_mixed(&mut self, src: impl Into<textual::Expr>) -> Result<Sid> { self.fb.load(&textual::Ty::mixed_ptr(), src) } fn load_this(&mut self) -> Result<textual::Sid> { let var = LocalId::Named(self.strings.intern_str(special_idents::THIS)); let mi = self.expect_method_info(); let ty = mi.class_ty(); let this = self.fb.load(&ty, textual::Expr::deref(var))?; Ok(this) } pub(crate) fn lookup_iid(&self, iid: InstrId) -> textual::Expr { if let Some(expr) = self.iid_mapping.get(&iid) { return expr.clone(); } // The iid wasn't found. Maybe it's a "special" reference (like a // Deref()) - pessimistically look for that. match self.func.instr(iid) { Instr::Special(Special::Textual(Textual::Deref(lid))) => { return textual::Expr::deref(*lid); } _ => {} } panic!("failed to look up iid {iid}"); } /// Look up a ValueId in the FuncState and return an Expr representing /// it. For InstrIds and complex ConstIds return an Expr containing the /// (already emitted) Sid. For simple ConstIds use an Expr representing the /// value directly. pub(crate) fn lookup_vid(&mut self, vid: ValueId) -> textual::Expr { match vid.full() { ir::FullInstrId::Instr(iid) => self.lookup_iid(iid), ir::FullInstrId::Constant(c) => { use hack::Builtin; use ir::CollectionType; let c = self.func.constant(c); match c { Constant::Bool(false) => hack::expr_builtin(Builtin::Bool, [false]), Constant::Bool(true) => hack::expr_builtin(Builtin::Bool, [true]), Constant::Int(i) => hack::expr_builtin(Builtin::Int, [*i]), Constant::Null => textual::Expr::null(), Constant::String(s) => { let s = self.strings.lookup_bstr(*s); let s = util::escaped_string(&s); hack::expr_builtin(Builtin::String, [s]) } Constant::Array(..) => textual_todo! { textual::Expr::null() }, Constant::Dir => textual_todo! { textual::Expr::null() }, Constant::Float(f) => hack::expr_builtin(Builtin::Float, [f.to_f64()]), Constant::File => textual_todo! { textual::Expr::null() }, Constant::FuncCred => textual_todo! { textual::Expr::null() }, Constant::Method => textual_todo! { textual::Expr::null() }, Constant::NewCol(CollectionType::ImmMap) => { hack::expr_builtin(Builtin::Hhbc(hack::Hhbc::NewColImmMap), ()) } Constant::NewCol(CollectionType::ImmSet) => { hack::expr_builtin(Builtin::Hhbc(hack::Hhbc::NewColImmSet), ()) } Constant::NewCol(CollectionType::ImmVector) => { hack::expr_builtin(Builtin::Hhbc(hack::Hhbc::NewColImmVector), ()) } Constant::NewCol(CollectionType::Map) => { hack::expr_builtin(Builtin::Hhbc(hack::Hhbc::NewColMap), ()) } Constant::NewCol(CollectionType::Pair) => { hack::expr_builtin(Builtin::Hhbc(hack::Hhbc::NewColPair), ()) } Constant::NewCol(CollectionType::Set) => { hack::expr_builtin(Builtin::Hhbc(hack::Hhbc::NewColSet), ()) } Constant::NewCol(CollectionType::Vector) => { hack::expr_builtin(Builtin::Hhbc(hack::Hhbc::NewColVector), ()) } Constant::Uninit => textual::Expr::null(), Constant::Named(..) | Constant::NewCol(_) => unreachable!(), } } ir::FullInstrId::None => unreachable!(), } } pub(crate) fn set_iid(&mut self, iid: InstrId, expr: impl Into<textual::Expr>) { let expr = expr.into(); let old = self.iid_mapping.insert(iid, expr); assert!(old.is_none()); } pub(crate) fn store_mixed( &mut self, dst: impl Into<textual::Expr>, src: impl Into<textual::Expr>, ) -> Result { self.fb.store(dst, src, &textual::Ty::mixed_ptr()) } pub(crate) fn update_loc(&mut self, loc: LocId) -> Result { if loc != LocId::NONE { let new = &self.func.locs[loc]; self.fb.write_loc(new)?; } Ok(()) } pub(crate) fn write_todo(&mut self, msg: &str) -> Result<Sid> { textual_todo! { message = ("TODO: {msg}"), let target = FunctionName::Unmangled(format!("$todo.{msg}")); self.fb.call(&target, ()) } } } /// Convert from a deterministic jump model to a non-deterministic model. /// /// In Textual instead of "jump if" you say "jump to a, b" and then in 'a' and 'b' /// you say "stop if my condition isn't met". /// /// This inserts the needed 'assert_true' and 'assert_false' statements but /// leaves the original JmpOp as a marker for where to jump to. fn rewrite_jmp_ops<'a>(mut func: ir::Func<'a>) -> ir::Func<'a> { for bid in func.block_ids() { match *func.terminator(bid) { Terminator::JmpOp { cond, pred, targets: [mut true_bid, mut false_bid], loc, } => { // We need to rewrite this jump. Because we don't allow critical // edges we can just insert the 'assert' at the start of the // target block since we must be the only caller. trace!(" JmpOp at {bid} needs to be rewritten"); match pred { Predicate::Zero => { std::mem::swap(&mut true_bid, &mut false_bid); } Predicate::NonZero => {} } let iid = func.alloc_instr(Instr::Special(Special::Textual(Textual::AssertTrue( cond, loc, )))); func.block_mut(true_bid).iids.insert(0, iid); let iid = func.alloc_instr(Instr::Special(Special::Textual(Textual::AssertFalse( cond, loc, )))); func.block_mut(false_bid).iids.insert(0, iid); } _ => {} } } func } #[derive(Clone)] pub(crate) enum FuncInfo<'a> { Function(FunctionInfo), Method(MethodInfo<'a>), } impl<'a> FuncInfo<'a> { pub(crate) fn expect_method(&self, why: &str) -> &MethodInfo<'a> { match self { FuncInfo::Function(_) => panic!("{}", why), FuncInfo::Method(mi) => mi, } } pub(crate) fn name_id(&self) -> ir::UnitBytesId { match self { FuncInfo::Function(fi) => fi.name.id, FuncInfo::Method(mi) => mi.name.id, } } pub(crate) fn attrs(&self) -> &ir::Attr { match self { FuncInfo::Function(fi) => &fi.attrs, FuncInfo::Method(mi) => &mi.attrs, } } pub(crate) fn declared_in_trait(&self) -> bool { match self { FuncInfo::Function(_) => false, FuncInfo::Method(mi) => mi.declared_in_trait(), } } pub(crate) fn is_async(&self) -> bool { match self { FuncInfo::Function(fi) => fi.flags.contains(FunctionFlags::ASYNC), FuncInfo::Method(mi) => mi.flags.contains(MethodFlags::IS_ASYNC), } } } // Extra data associated with a (non-class) function that aren't stored on the // Func. #[derive(Clone)] pub(crate) struct FunctionInfo { pub(crate) name: FunctionId, pub(crate) attrs: ir::Attr, pub(crate) flags: FunctionFlags, } // Extra data associated with class methods that aren't stored on the Func. #[derive(Clone)] pub(crate) struct MethodInfo<'a> { pub(crate) name: MethodId, pub(crate) attrs: ir::Attr, pub(crate) class: &'a ir::Class<'a>, pub(crate) is_static: IsStatic, pub(crate) flags: MethodFlags, } impl MethodInfo<'_> { pub(crate) fn non_static_ty(&self) -> textual::Ty { class::non_static_ty(self.class.name) } pub(crate) fn class_ty(&self) -> textual::Ty { class::class_ty(self.class.name, self.is_static) } pub(crate) fn declared_in_trait(&self) -> bool { self.class.is_trait() } } /// Compare locals such that named ones go first followed by unnamed ones. /// Ordering for named locals is stable and is based on their source names. /// Unnamed locals have only their id which may differ accross runs. In which /// case the IR would be non-deterministic and hence unstable ordering would be /// the least of our concerns. fn cmp_lid(strings: &StringInterner, x: &LocalId, y: &LocalId) -> std::cmp::Ordering { match (x, y) { (LocalId::Named(x_bid), LocalId::Named(y_bid)) => { let x_name = strings.lookup_bytes(*x_bid); let y_name = strings.lookup_bytes(*y_bid); x_name.cmp(&y_name) } (LocalId::Named(_), LocalId::Unnamed(_)) => std::cmp::Ordering::Less, (LocalId::Unnamed(_), LocalId::Named(_)) => std::cmp::Ordering::Greater, (LocalId::Unnamed(x_id), LocalId::Unnamed(y_id)) => x_id.cmp(y_id), } } pub(crate) fn write_todo(fb: &mut textual::FuncBuilder<'_, '_>, msg: &str) -> Result<Sid> { trace!("TODO: {}", msg); textual_todo! { let target = FunctionName::Unmangled(format!("$todo.{msg}")); fb.call(&target, ()) } } pub(crate) fn lookup_constant<'a, 'b>( func: &'a Func<'b>, mut vid: ValueId, ) -> Option<&'a ir::Constant<'b>> { use ir::FullInstrId; loop { match vid.full() { FullInstrId::Instr(iid) => { let instr = func.instr(iid); match instr { // If the pointed-at instr is a copy then follow it and try // again. Instr::Special(Special::Copy(copy)) => { vid = *copy; } // SetL's output is just its input, updating the local is a // side-effect. Follow the input and try again. Instr::Hhbc(Hhbc::SetL(input_vid, _, _)) => { vid = *input_vid; } _ => return None, } } FullInstrId::Constant(cid) => { return Some(func.constant(cid)); } FullInstrId::None => { return None; } } } } pub(crate) fn lookup_constant_string(func: &Func<'_>, vid: ValueId) -> Option<ir::UnitBytesId> { match lookup_constant(func, vid) { Some(Constant::String(id)) => Some(*id), _ => None, } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/textual/hack.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use anyhow::Error; use hash::HashSet; use strum::EnumIter; use textual_macros::TextualDecl; use crate::mangle::FunctionName; use crate::textual; use crate::textual::Sid; use crate::textual::TextualFile; type Result<T = (), E = Error> = std::result::Result<T, E>; // TODO: Where should we define the builtin type hierarchy? // // class HackMixed { } // // class HackArray extends HackMixed { } // class HackBool extends HackMixed { } // class HackDict extends HackArray { } // class HackFloat extends HackMixed { } // class HackInt extends HackMixed { } // class HackKeyset extends HackArray { } // class HackString extends HackMixed { } // class HackVec extends HackArray { } // // type HackArraykey = HackInt | HackString; // type HackNum = HackInt | HackFloat; /// These represent builtins for handling HHVM bytecode instructions. In general /// the names should match the HHBC name except when they are compound bytecodes /// (like Cmp with a parameter of Eq becoming CmpEq). Documentation can be found /// in hphp/doc/bytecode.specification. #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)] #[derive(TextualDecl, EnumIter)] #[derive(Default)] pub(crate) enum Hhbc { #[decl(fn hhbc_add(*HackMixed, *HackMixed) -> *HackMixed)] #[default] Add, #[decl(fn hhbc_add_elem_c(*HackMixed, *HackMixed, *HackMixed) -> *HackMixed)] AddElemC, #[decl(fn hhbc_add_new_elem_c(*HackMixed, *HackMixed) -> *HackMixed)] AddNewElemC, #[decl(fn hhbc_await(*HackMixed) -> *HackMixed)] Await, #[decl(fn hhbc_await_all(...) -> *HackMixed)] AwaitAll, #[decl(fn hhbc_cast_keyset(*HackMixed) -> *HackMixed)] CastKeyset, #[decl(fn hhbc_cast_string(*HackMixed) -> *HackString)] CastString, #[decl(fn hhbc_cast_vec(*HackMixed) -> *HackMixed)] CastVec, #[decl(fn hhbc_class_get_c(*HackMixed) -> void)] CheckClsRGSoft, #[decl(fn hhbc_check_this(*HackMixed) -> void)] CheckThis, #[decl(fn hhbc_class_get_c(*HackMixed) -> *HackMixed)] ClassGetC, #[decl(fn hhbc_class_has_reified_generics(*HackMixed) -> *HackMixed)] ClassHasReifiedGenerics, #[decl(fn hhbc_cls_cns(*HackMixed, *HackString) -> *HackMixed)] ClsCns, #[decl(fn hhbc_cmp_eq(*HackMixed, *HackMixed) -> *HackMixed)] CmpEq, #[decl(fn hhbc_cmp_gt(*HackMixed, *HackMixed) -> *HackMixed)] CmpGt, #[decl(fn hhbc_cmp_gte(*HackMixed, *HackMixed) -> *HackMixed)] CmpGte, #[decl(fn hhbc_cmp_lt(*HackMixed, *HackMixed) -> *HackMixed)] CmpLt, #[decl(fn hhbc_cmp_lte(*HackMixed, *HackMixed) -> *HackMixed)] CmpLte, #[decl(fn hhbc_cmp_nsame(*HackMixed, *HackMixed) -> *HackMixed)] CmpNSame, #[decl(fn hhbc_cmp_neq(*HackMixed, *HackMixed) -> *HackMixed)] CmpNeq, #[decl(fn hhbc_cmp_same(*HackMixed, *HackMixed) -> *HackMixed)] CmpSame, // ColFromArray variations for different collection types #[decl(fn hhbc_col_from_array_imm_map(*HackMixed) -> *HackMixed)] ColFromArrayImmMap, #[decl(fn hhbc_col_from_array_imm_set(*HackMixed) -> *HackMixed)] ColFromArrayImmSet, #[decl(fn hhbc_col_from_array_imm_vector(*HackMixed) -> *HackMixed)] ColFromArrayImmVector, #[decl(fn hhbc_col_from_array_map(*HackMixed) -> *HackMixed)] ColFromArrayMap, #[decl(fn hhbc_col_from_array_pair(*HackMixed) -> *HackMixed)] ColFromArrayPair, #[decl(fn hhbc_col_from_array_set(*HackMixed) -> *HackMixed)] ColFromArraySet, #[decl(fn hhbc_col_from_array_vector(*HackMixed) -> *HackMixed)] ColFromArrayVector, // ColFromArray end #[decl(fn hhbc_combine_and_resolve_type_struct(...) -> *HackMixed)] CombineAndResolveTypeStruct, #[decl(fn hhbc_concat(*HackMixed, *HackMixed) -> *HackMixed)] Concat, #[decl(fn hhbc_concat(...) -> *HackMixed)] ConcatN, #[decl(fn hhbc_div(*HackMixed, *HackMixed) -> *HackMixed)] Div, #[decl(fn hhbc_exit(*HackMixed) -> noreturn)] Exit, #[decl(fn hhbc_fatal(*HackMixed) -> noreturn)] Fatal, #[decl(fn hhbc_get_cls_rg_prop(*HackMixed) -> *HackMixed)] GetClsRGProp, #[decl(fn hhbc_get_memo_key_l(*HackMixed) -> *HackMixed)] GetMemoKeyL, #[decl(fn hhbc_has_reified_parent(*HackMixed) -> *HackMixed)] HasReifiedParent, #[decl(fn hhbc_idx(*HackMixed, *HackMixed) -> *HackMixed)] Idx, #[decl(fn hhbc_is_late_bound_cls(*HackMixed) -> *HackMixed)] IsLateBoundCls, #[decl(fn hhbc_is_type_arr_like(*HackMixed) -> *HackMixed)] IsTypeArrLike, #[decl(fn hhbc_is_type_bool(*HackMixed) -> *HackMixed)] IsTypeBool, #[decl(fn hhbc_is_type_class(*HackMixed) -> *HackMixed)] IsTypeClass, #[decl(fn hhbc_is_type_cls_meth(*HackMixed) -> *HackMixed)] IsTypeClsMeth, #[decl(fn hhbc_is_type_dbl(*HackMixed) -> *HackMixed)] IsTypeDbl, #[decl(fn hhbc_is_type_dict(*HackMixed) -> *HackMixed)] IsTypeDict, #[decl(fn hhbc_is_type_func(*HackMixed) -> *HackMixed)] IsTypeFunc, #[decl(fn hhbc_is_type_int(*HackMixed) -> *HackMixed)] IsTypeInt, #[decl(fn hhbc_is_type_keyset(*HackMixed) -> *HackMixed)] IsTypeKeyset, #[decl(fn hhbc_is_type_legacy_arr_like(*HackMixed) -> *HackMixed)] IsTypeLegacyArrLike, #[decl(fn hhbc_is_type_null(*HackMixed) -> *HackMixed)] IsTypeNull, #[decl(fn hhbc_is_type_obj(*HackMixed) -> *HackMixed)] IsTypeObj, #[decl(fn hhbc_is_type_res(*HackMixed) -> *HackMixed)] IsTypeRes, #[decl(fn hhbc_is_type_scalar(*HackMixed) -> *HackMixed)] IsTypeScalar, #[decl(fn hhbc_is_type_str(*HackMixed) -> *HackMixed)] IsTypeStr, #[decl(fn hhbc_is_type_struct_c(*HackMixed, *HackMixed, *HackMixed) -> *HackMixed)] IsTypeStructC, #[decl(fn hhbc_is_type_vec(*HackMixed) -> *HackMixed)] IsTypeVec, #[decl(fn hhbc_iter_free(it: *Iterator) -> void)] IterFree, #[decl(fn hhbc_iter_init(it: **Iterator, key: **HackMixed, var: **HackMixed, container: *HackMixed) -> *HackBool)] IterInit, #[decl(fn hhbc_iter_next(it: *Iterator, key: **HackMixed, var: **HackMixed) -> *HackBool)] IterNext, #[decl(fn hhbc_lazy_class_from_class(*HackMixed) -> *HackString)] LazyClassFromClass, #[decl(fn hhbc_lock_obj(*HackMixed) -> void)] LockObj, #[decl(fn hhbc_memo_set(...) -> *HackMixed)] MemoSet, #[decl(fn hhbc_modulo(*HackMixed, *HackMixed) -> *HackMixed)] Modulo, #[decl(fn hhbc_mul(*HackMixed, *HackMixed) -> *HackMixed)] Mul, #[decl(fn hhbc_new_col_imm_map() -> *HackMixed)] NewColImmMap, #[decl(fn hhbc_new_col_imm_set() -> *HackMixed)] NewColImmSet, #[decl(fn hhbc_new_col_imm_vector() -> *HackMixed)] NewColImmVector, #[decl(fn hhbc_new_col_map() -> *HackMixed)] NewColMap, #[decl(fn hhbc_new_col_pair() -> *HackMixed)] NewColPair, #[decl(fn hhbc_new_col_set() -> *HackMixed)] NewColSet, #[decl(fn hhbc_new_col_vector() -> *HackMixed)] NewColVector, #[decl(fn hhbc_new_dict() -> *HackMixed)] NewDictArray, #[decl(fn hhbc_new_keyset_array(...) -> *HackMixed)] NewKeysetArray, #[decl(fn hhbc_new_vec(...) -> *HackVec)] NewVec, #[decl(fn hhbc_not(*HackMixed) -> *HackMixed)] Not, #[decl(fn hhbc_print(*HackMixed) -> *HackMixed)] Print, #[decl(fn hhbc_record_reified_generic(*HackMixed) -> *HackMixed)] RecordReifiedGeneric, #[decl(fn hhbc_sub(*HackMixed, *HackMixed) -> *HackMixed)] Sub, #[decl(fn hhbc_throw(*HackMixed) -> noreturn)] Throw, #[decl(fn hhbc_throw_as_type_struct_exception(*HackMixed, *HackMixed) -> *HackMixed)] ThrowAsTypeStructException, #[decl(fn hhbc_throw_non_exhaustive_switch() -> noreturn)] ThrowNonExhaustiveSwitch, #[decl(fn hhbc_verify_param_type_ts(obj: *HackMixed, ts: *HackMixed) -> void)] VerifyParamTypeTS, #[decl(fn hhbc_wh_result(obj: *HackMixed) -> *HackMixed)] WHResult, } #[derive(Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Debug)] #[derive(TextualDecl, EnumIter)] pub(crate) enum Builtin { /// Allocate an array with the given number of words (a word is a /// pointer-sized value). #[decl(fn alloc_words(int) -> *void)] AllocWords, /// Turns a raw boolean into a HackMixed. #[decl(fn hack_bool(int) -> *HackBool)] Bool, /// Get the value of a named field from a struct. #[decl(fn hack_field_get(base: *HackMixed, name: *HackMixed) -> *HackMixed)] FieldGet, /// Turns a raw float into a Mixed. #[decl(fn hack_float(float) -> *HackFloat)] Float, /// Returns the Class identifier for the given class. #[decl(fn hack_get_class(*void) -> *class)] GetClass, /// Returns the Class identifier for the given class's static class. #[decl(fn hack_get_static_class(*void) -> *class)] GetStaticClass, /// Get the named superglobal. #[decl(fn hack_get_superglobal(name: *HackMixed) -> *HackMixed)] GetSuperglobal, /// Like HackArrayCowSet but appends the value to the previous array and /// returns the copied base array. /// /// This is equivalent to the sequence: /// a = ensure_unique(a) /// a[b] = ensure_unique(a[b]) /// a[b][] = c /// #[decl(fn hack_array_cow_append(...) -> *HackMixed)] HackArrayCowAppend, /// n-ary array "set". /// /// Performs the n-ary array "set" operation but ensures that the arrays /// along the way are unique and then updates the final value. Returns the /// copied base array. /// /// This is equivalent to the sequence: /// a = ensure_unique(a) /// a[b] = ensure_unique(a[b]) /// a[b][c] = d /// #[decl(fn hack_array_cow_set(...) -> *HackMixed)] HackArrayCowSet, /// n-ary array "get" /// /// Performs the n-ary array "get" operation without any copies and returns /// the tail value. /// /// This is equivalent to `a[b][c]`. /// #[decl(fn hack_array_get(...) -> *HackMixed)] HackArrayGet, /// 1-ary prop "get". /// /// Dynamically fetches the value from the named key of the instance. /// /// If null_safe is true then a base of null returns null. /// /// This (when null_safe is false) is equivalent to: /// base.?.{dynamic key} /// #[decl(fn hack_prop_get(base: *HackMixed, key: *HackMixed, null_safe: int) -> *HackMixed)] HackPropGet, /// 1-ary prop "set". /// /// Dynamically stores the value into the named key of the instance. /// /// If null_safe is true then a base of null is a no-op. /// /// This (when null_safe is false) is equivalent to: /// base.?.{dynamic key} = value /// #[decl(fn hack_prop_set(base: *HackMixed, key: *HackMixed, null_safe: int, value: *HackMixed) -> void)] HackPropSet, /// Hhbc handlers. See hphp/doc/bytecode.specification for docs. #[decl(skip)] Hhbc(Hhbc), /// Turns a raw int into a HackMixed. #[decl(fn hack_int(int) -> *HackInt)] Int, /// Returns true if the given HackMixed is truthy. #[decl(fn hack_is_true(*HackMixed) -> int)] IsTrue, /// Returns true if the given object is of the named type. #[decl(fn hack_is_type(obj: *HackMixed, ty: *HackString) -> *HackMixed)] IsType, /// Merge the given values into a single hash key and return the memoized /// value. /// (&global, ops) #[decl(fn hack_memo_get(...) -> *HackMixed)] MemoGet, /// Merge the given values into a single hash key and return true if the /// memo key is already set. /// (&global, ops) #[decl(fn hack_memo_isset(...) -> *HackMixed)] MemoIsset, /// Build a dict based on key/value pairs. #[decl(fn hack_new_dict(...) -> *HackMixed)] NewDict, #[decl(fn hack_set_static_prop(classname: string, propname: string, value: *HackArray) -> void)] SetStaticProp, /// Set the named superglobal. #[decl(fn hack_get_superglobal(name: *HackMixed, value: *HackMixed) -> void)] SetSuperglobal, /// Note that this argument is a 'splat' (unwrapped array args for a function). #[decl(fn __sil_splat(*HackArray) -> *HackArray)] SilSplat, /// Turns a raw string into a HackMixed. #[decl(fn hack_string(string) -> *HackString)] String, /// Checks that the predicate is true or throws a VerifyType error. #[decl(fn hhbc_verify_type_pred(obj: *HackMixed, pred: *HackMixed) -> void)] VerifyTypePred, } pub(crate) fn call_builtin( fb: &mut textual::FuncBuilder<'_, '_>, target: Builtin, params: impl textual::VarArgs, ) -> Result<Sid> { fb.call(&FunctionName::Builtin(target), params) } pub(crate) fn expr_builtin(target: Builtin, params: impl textual::VarArgs) -> textual::Expr { textual::Expr::call(FunctionName::Builtin(target), params) }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/textual/lib.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. //! Textual is the name of the text format for Infer's IR. This crate converts //! from HackC's IR to Textual for ingestion by Infer. //! //! End-to-end usage example: //! hackc compile-infer test/infer/basic.hack > basic.sil //! ./infer/bin/infer compile --capture-textual basic.sil #![feature(box_patterns)] pub static KEEP_GOING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); pub fn keep_going_mode() -> bool { KEEP_GOING.load(std::sync::atomic::Ordering::Acquire) } // If KEEP_GOING is false then execute a 'todo!' otherwise call the function. // // Used like: // textual_todo! { w.comment("TODO: Try-Catch Block")? }; #[allow(unused)] macro_rules! textual_todo { ( message = ($($msg:expr),+), $($rest:tt)+ ) => { (if $crate::keep_going_mode() { $($rest)+ } else { todo!($($msg),+) }) }; ( $($rest:tt)+ ) => { (if $crate::keep_going_mode() { $($rest)+ } else { todo!() }) }; } mod class; mod decls; mod func; mod hack; mod lower; mod mangle; mod member_op; mod state; mod textual; mod typed_value; mod types; mod util; mod writer; pub use writer::textual_writer;
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/textual/macros.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. #![feature(box_patterns)] use itertools::Itertools; use proc_macro2::Literal; use proc_macro2::TokenStream; use proc_macro_error::abort; use proc_macro_error::proc_macro_error; use proc_macro_error::ResultExt; use quote::quote; use syn::parenthesized; use syn::parse::Parse; use syn::parse::ParseStream; use syn::parse_macro_input; use syn::punctuated::Punctuated; use syn::token; use syn::Attribute; use syn::DeriveInput; use syn::Ident; use syn::Result; use syn::Token; /// This macro is used to derive the TextualDecl trait for builtins. /// /// When applied to an enum expects that each variant has an attribute in the form: /// #[decl(fn name(ty1, ty2) -> ty, opts...)] /// /// opts can be: /// can_write - this function writes to memory. This isn't currently used and /// is basically a placeholder for other decl options. /// /// and it generates an impl: /// impl ... { /// /// Write the listed set of decls to the TextualFile. /// fn write_decls(w: &mut TextualFile<'_>, subset: &HashSet<Name>) -> Result<()> { ... } /// /// /// Returns a string representing the builtin declaration. /// fn as_str(&self) -> &'static str; /// /// /// Returns `true` if the builtin can write to memory. /// fn can_write(&self) -> bool; /// } /// /// It also implements the Display trait for the enum. /// #[proc_macro_error] #[proc_macro_derive(TextualDecl, attributes(decl, function))] pub fn textual_decl_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = parse_macro_input!(input as DeriveInput); let name = &input.ident; let vis = &input.vis; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let mut last = None; let mut decls: Vec<TokenStream> = Vec::new(); let mut displays: Vec<TokenStream> = Vec::new(); let mut can_writes: Vec<TokenStream> = Vec::new(); match input.data { syn::Data::Enum(e) => { for variant in e.variants { let variant_name = &variant.ident; let attr = extract_exactly_one_attr(&variant.ident, variant.attrs, "decl"); let decl: Decl = syn::parse2(attr.tokens).unwrap_or_abort(); // Enforce sorted variant order. let variant_name_str = format!("{variant_name}"); if let Some(last_str) = last { if last_str > variant_name_str { abort!( variant_name, format!( "Variants are out of order - '{last_str}' must be after '{variant_name_str}'" ) ); } } last = Some(variant_name_str); match decl { Decl::FnSignature { signature, can_write, } => { let builtin_name = Literal::string(&format!("$builtins.{}", signature.ident)); let params = signature .parameters .iter() .map(|p| { let (ty, owned) = p.ty.tokenize(); if owned { quote!(#ty) } else { ty } }) .collect_vec(); let ret = { let (ty, owned) = signature.ret.tokenize(); if owned { quote!(#ty) } else { ty } }; let fn_name = if name == "Hhbc" { quote!(crate::mangle::FunctionName::Builtin(Builtin::Hhbc(Hhbc::#variant_name))) } else { quote!(crate::mangle::FunctionName::Builtin(#name::#variant_name)) }; let decl = quote! { if subset.contains(&#name::#variant_name) { txf.declare_function(&#fn_name, &textual::FuncAttributes::default(), &[#(#params),*], &#ret)?; } }; decls.push(decl); let display = quote!(#name::#variant_name => #builtin_name,); displays.push(display); let can_write = quote!(#name::#variant_name => #can_write,); can_writes.push(can_write); } Decl::Skip => { displays.push(quote!(#name::#variant_name(f) => f.as_str(),)); can_writes.push(quote!(#name::#variant_name(f) => f.can_write(),)); } } } } syn::Data::Struct(s) => abort!(s.struct_token, "TextualDecl does not support 'struct'"), syn::Data::Union(u) => abort!(u.union_token, "TextualDecl does not support 'union'"), } let output = quote! { impl #impl_generics #name #ty_generics #where_clause { #vis fn write_decls(txf: &mut TextualFile<'_>, subset: &HashSet<#name #ty_generics>) -> Result<()> { #(#decls)* Ok(()) } #vis fn as_str(&self) -> &'static str { match self { #(#displays)* } } #vis fn can_write(&self) -> bool { match self { #(#can_writes)* } } } }; output.into() } fn extract_exactly_one_attr(ident: &Ident, attrs: Vec<Attribute>, name: &str) -> Attribute { let mut attrs = attrs.into_iter().filter(|attr| attr.path.is_ident(name)); let attr = if let Some(attr) = attrs.next() { attr } else { abort!(ident, "variant is missing 'decl' attribute"); }; if let Some(next) = attrs.next() { abort!( next.path, "'decl' attribute may not be specified multiple times" ); } attr } enum Decl { FnSignature { signature: DeclSig, can_write: bool }, Skip, } impl Parse for Decl { fn parse(wrapped_input: ParseStream<'_>) -> Result<Self> { let input; parenthesized!(input in wrapped_input); let signature = if input.peek(Token![fn]) { let args; DeclSig { fn_token: input.parse()?, ident: input.parse()?, paren_token: parenthesized!(args in input), parameters: args.parse_terminated(DeclArg::parse)?, arrow: input.parse()?, ret: input.parse()?, } } else { let tag: Ident = input.parse()?; if tag == "skip" { if !input.is_empty() { return Err(input.error("'skip' may not be followed by additional tokens")); } return Ok(Decl::Skip); } else { abort!(tag, "Unknown 'decl' type"); } }; let mut can_write = false; while input.peek(Token![,]) { let _t: Token![,] = input.parse()?; let name: Ident = input.parse()?; if name == "can_write" { can_write = true; } else { return Err(input.error("unknown decl")); } } if !input.is_empty() { return Err(input.error("unexpected input")); } Ok(Decl::FnSignature { signature, can_write, }) } } struct DeclSig { #[allow(dead_code)] fn_token: token::Fn, ident: Ident, #[allow(dead_code)] paren_token: token::Paren, parameters: Punctuated<DeclArg, token::Comma>, #[allow(dead_code)] arrow: token::RArrow, ret: DeclTy, } struct DeclArg { #[allow(dead_code)] name: Option<(Ident, token::Colon)>, ty: DeclTy, } impl Parse for DeclArg { fn parse(input: ParseStream<'_>) -> Result<Self> { let name = if input.peek2(Token![:]) { let name: Ident = input.parse()?; let colon: token::Colon = input.parse()?; Some((name, colon)) } else { None }; let ty = input.parse()?; Ok(DeclArg { name, ty }) } } #[derive(Debug)] enum DeclTy { Ellipsis(token::Dot3), Float(Ident), Int(Ident), Noreturn(Ident), Ptr(token::Star, Box<DeclTy>), String(Ident), Type(Ident), Void(Ident), } impl Parse for DeclTy { fn parse(input: ParseStream<'_>) -> Result<Self> { if input.peek(Token![*]) { Ok(DeclTy::Ptr(input.parse()?, Box::new(input.parse()?))) } else if input.peek(Token![...]) { Ok(DeclTy::Ellipsis(input.parse()?)) } else if input.peek(Ident) { let id: Ident = input.parse()?; if id == "float" { Ok(DeclTy::Float(id)) } else if id == "int" { Ok(DeclTy::Int(id)) } else if id == "noreturn" { Ok(DeclTy::Noreturn(id)) } else if id == "string" { Ok(DeclTy::String(id)) } else if id == "void" { Ok(DeclTy::Void(id)) } else { Ok(DeclTy::Type(id)) } } else { use syn::ext::IdentExt; let id = Ident::parse_any(input)?; abort!(id, "Unexpected token"); } } } impl DeclTy { fn tokenize(&self) -> (TokenStream, bool) { match self { // a couple special cases first DeclTy::Ptr(_, box DeclTy::Void(_)) => (quote!(textual::Ty::VoidPtr), false), DeclTy::Ptr(_, box DeclTy::Type(id)) if id == "HackMixed" => { (quote!(textual::Ty::mixed_ptr()), false) } DeclTy::Ellipsis(_) => (quote!(textual::Ty::Ellipsis), true), DeclTy::Float(_) => (quote!(textual::Ty::Float), true), DeclTy::Int(_) => (quote!(textual::Ty::Int), true), DeclTy::Noreturn(_) => (quote!(textual::Ty::Noreturn), true), DeclTy::Ptr(_, box sub) => { let (mut sub, sub_owned) = sub.tokenize(); if !sub_owned { sub = quote!(#sub.clone()); } (quote!(textual::Ty::Ptr(Box::new(#sub))), true) } DeclTy::String(_) => (quote!(textual::Ty::String), true), DeclTy::Type(name) => { let name = format!("{name}"); ( quote!(textual::Ty::Type(crate::mangle::TypeName::UnmangledRef(#name))), true, ) } DeclTy::Void(_) => (quote!(textual::Ty::Void), true), } } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/textual/mangle.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::cmp::Ordering; use std::fmt; use ir::StringInterner; use naming_special_names_rust::members; use crate::class::IsStatic; pub(crate) const TOP_LEVELS_CLASS: &str = "$root"; /// Used for things that can mangle themselves directly. pub(crate) trait Mangle { fn mangle(&self, strings: &StringInterner) -> String; } impl Mangle for [u8] { fn mangle(&self, _strings: &StringInterner) -> String { // Handle some reserved tokens. match self { b"declare" => "declare_".to_owned(), b"define" => "define_".to_owned(), b"extends" => "extends_".to_owned(), b"false" => "false_".to_owned(), b"float" => "float_".to_owned(), b"global" => "global_".to_owned(), b"int" => "int_".to_owned(), b"jmp" => "jmp_".to_owned(), b"load" => "load_".to_owned(), b"local" => "local_".to_owned(), b"null" => "null_".to_owned(), b"prune" => "prune_".to_owned(), b"ret" => "ret_".to_owned(), b"store" => "store_".to_owned(), b"throw" => "throw_".to_owned(), b"true" => "true_".to_owned(), b"type" => "type_".to_owned(), b"unreachable" => "unreachable_".to_owned(), b"void" => "void_".to_owned(), _ => { // This mangling is terrible... but probably "good enough". // If a digit is first then we prepend a '_'. // [A-Za-z0-9_$] -> identity // \ -> :: // anything else -> xx (hex digits) let mut res = String::with_capacity(self.len()); if self.first().map_or(false, u8::is_ascii_digit) { res.push('_'); } for &ch in self { match ch { b'_' | b'$' => res.push(ch as char), b'\\' => { res.push(':'); res.push(':'); } ch if ch.is_ascii_alphanumeric() => res.push(ch as char), _ => { res.push(b"0123456789abcdef"[(ch >> 4) as usize] as char); res.push(b"0123456789abcdef"[(ch & 15) as usize] as char); } } } res } } } } // Classes and functions live in different namespaces. impl Mangle for ir::PropId { fn mangle(&self, strings: &StringInterner) -> String { self.as_bytes(strings).mangle(strings) } } #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub(crate) enum Intrinsic { ConstInit(ir::ClassId), Construct(ir::ClassId), Factory(ir::ClassId), Invoke(TypeName), PropInit(ir::ClassId), StaticInit(ir::ClassId), } impl Intrinsic { pub(crate) fn contains_unknown(&self) -> bool { match self { Intrinsic::ConstInit(_) | Intrinsic::Construct(_) | Intrinsic::Factory(_) | Intrinsic::PropInit(_) | Intrinsic::StaticInit(_) => false, Intrinsic::Invoke(name) => *name == TypeName::Unknown, } } } /// Represents a named callable thing. This includes top-level functions and /// methods. #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub(crate) enum FunctionName { Builtin(crate::hack::Builtin), Function(ir::FunctionId), Intrinsic(Intrinsic), Method(TypeName, ir::MethodId), Unmangled(String), } impl FunctionName { pub(crate) fn method(class: ir::ClassId, is_static: IsStatic, method: ir::MethodId) -> Self { Self::Method(TypeName::class(class, is_static), method) } pub(crate) fn untyped_method(method: ir::MethodId) -> Self { Self::Method(TypeName::Unknown, method) } pub(crate) fn display<'r>(&'r self, strings: &'r StringInterner) -> impl fmt::Display + 'r { FmtFunctionName(strings, self) } pub(crate) fn cmp(&self, other: &Self, strings: &StringInterner) -> Ordering { let a = self.display(strings).to_string(); let b = other.display(strings).to_string(); a.cmp(&b) } pub(crate) fn contains_unknown(&self) -> bool { match self { FunctionName::Builtin(_) | FunctionName::Function(_) | FunctionName::Unmangled(_) => { false } FunctionName::Intrinsic(intrinsic) => intrinsic.contains_unknown(), FunctionName::Method(name, _) => *name == TypeName::Unknown, } } } struct FmtFunctionName<'a>(&'a StringInterner, &'a FunctionName); impl fmt::Display for FmtFunctionName<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let FmtFunctionName(strings, name) = *self; match name { FunctionName::Builtin(b) => b.as_str().fmt(f)?, FunctionName::Function(fid) => write!( f, "{TOP_LEVELS_CLASS}.{}", fid.as_bytes(strings).mangle(strings) )?, FunctionName::Intrinsic(intrinsic) => { let tn; let (ty, name) = match intrinsic { Intrinsic::ConstInit(cid) => { tn = TypeName::StaticClass(*cid); (Some(&tn), "_86cinit") } Intrinsic::Construct(cid) => { tn = TypeName::Class(*cid); (Some(&tn), members::__CONSTRUCT) } Intrinsic::Factory(cid) => { tn = TypeName::StaticClass(*cid); (Some(&tn), "__factory") } Intrinsic::Invoke(tn) => (Some(tn), "__invoke"), Intrinsic::PropInit(cid) => { tn = TypeName::Class(*cid); (Some(&tn), "_86pinit") } Intrinsic::StaticInit(cid) => { tn = TypeName::StaticClass(*cid); (Some(&tn), "_86sinit") } }; if let Some(ty) = ty { write!(f, "{}.{}", ty.display(strings), name)?; } else { f.write_str(name)?; } } FunctionName::Method(class, mid) => { write!( f, "{}.{}", class.display(strings), mid.as_bytes(strings).mangle(strings) )?; } FunctionName::Unmangled(s) => s.fmt(f)?, } Ok(()) } } #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub(crate) enum GlobalName { Global(ir::GlobalId), GlobalConst(ir::GlobalId), } impl GlobalName { pub(crate) fn display<'r>(&'r self, strings: &'r StringInterner) -> impl fmt::Display + 'r { FmtGlobalName(strings, self) } pub(crate) fn cmp(&self, other: &Self, strings: &StringInterner) -> Ordering { let a = self.display(strings).to_string(); let b = other.display(strings).to_string(); a.cmp(&b) } } struct FmtGlobalName<'a>(&'a StringInterner, &'a GlobalName); impl fmt::Display for FmtGlobalName<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let FmtGlobalName(strings, name) = *self; match name { GlobalName::Global(id) => { write!(f, "global::{}", id.as_bytes(strings).mangle(strings)) } GlobalName::GlobalConst(id) => { write!(f, "gconst::{}", id.as_bytes(strings).mangle(strings)) } } } } #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub(crate) enum TypeName { Class(ir::ClassId), Curry(Box<FunctionName>), StaticClass(ir::ClassId), Unknown, UnmangledRef(&'static str), } impl TypeName { pub(crate) fn class(class: ir::ClassId, is_static: crate::class::IsStatic) -> Self { match is_static { IsStatic::Static => Self::StaticClass(class), IsStatic::NonStatic => Self::Class(class), } } pub(crate) fn display<'r>(&'r self, strings: &'r StringInterner) -> impl fmt::Display + 'r { FmtTypeName(strings, self) } } struct FmtTypeName<'a>(&'a StringInterner, &'a TypeName); impl fmt::Display for FmtTypeName<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let FmtTypeName(strings, name) = *self; match name { TypeName::Class(cid) => f.write_str(&cid.as_bytes(strings).mangle(strings)), TypeName::Curry(box FunctionName::Function(fid)) => { write!(f, "{}$curry", fid.as_bytes(strings).mangle(strings)) } TypeName::Curry(box FunctionName::Method(ty, mid)) => { write!( f, "{}_{}$curry", ty.display(strings), mid.as_bytes(strings).mangle(strings) ) } TypeName::Curry(_) => panic!("Unable to name curry type {name:?}"), TypeName::Unknown => f.write_str("?"), TypeName::StaticClass(cid) => { f.write_str(&cid.as_bytes(strings).mangle(strings))?; f.write_str("$static") } TypeName::UnmangledRef(s) => s.fmt(f), } } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/textual/member_op.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use anyhow::bail; use anyhow::Error; use ir::instr::BaseOp; use ir::instr::FinalOp; use ir::instr::MemberKey; use ir::InstrId; use ir::LocalId; use ir::QueryMOp; use ir::ValueId; use itertools::Itertools; use naming_special_names_rust::special_idents; use textual::Expr; use textual::Ty; use crate::func::FuncState; use crate::hack; use crate::textual; use crate::textual::Sid; type Result<T = (), E = Error> = std::result::Result<T, E>; /// Intrinsics used by member operations: /// /// hack_array_cow_append /// hack_array_cow_set /// hack_array_get /// hack_get_superglobal /// hack_prop_get /// hack_prop_set /// hack_set_superglobal /// /// We break down member operations into sequences of hack_array_get() and /// property accesses. /// /// $a[k1][k2]->p1[k3][k4] = v1; /// /// Becomes: /// n0 = hack_array_get($a, k1, k2) /// n1: *HackMixed = load n0.?.p1 /// n2 = hack_array_set(n1, k3, k4, v1) /// store n1 <- n2: *HackMixed /// pub(crate) fn write( state: &mut FuncState<'_, '_, '_>, iid: InstrId, mop: &ir::instr::MemberOp, ) -> Result { let sid = emit_mop(state, mop)?; state.set_iid(iid, sid); Ok(()) } fn emit_mop(state: &mut FuncState<'_, '_, '_>, mop: &ir::instr::MemberOp) -> Result<Sid> { let mut locals = mop.locals.iter().copied(); let mut operands = mop.operands.iter().copied(); let mut emitter = MemberOpEmitter::new(state, &mut locals, &mut operands)?; emitter.write_base(&mop.base_op)?; for intermediate in mop.intermediate_ops.iter() { emitter.write_entry(&intermediate.key)?; } match &mop.final_op { FinalOp::SetRangeM { .. } => todo!(), op => emitter.finish(op), } } #[derive(Copy, Clone)] enum PropOp { NullThrows, NullSafe, } enum Base { Field { base: Sid, prop: Expr, op: PropOp }, Local(LocalId), Superglobal(Expr), Value(Expr), } impl Base { fn load(&self, state: &mut FuncState<'_, '_, '_>) -> Result<Sid> { use textual::Const; match *self { Base::Field { base, prop: Expr::Const(Const::String(ref key)), op: PropOp::NullThrows, } => state.load_mixed(Expr::field(base, Ty::unknown(), key.clone())), Base::Field { base, ref prop, op } => { let null_safe = match op { PropOp::NullThrows => Const::False, PropOp::NullSafe => Const::True, }; state.call_builtin( hack::Builtin::HackPropGet, (base, prop.clone(), Expr::Const(null_safe)), ) } Base::Local(lid) => state.load_mixed(Expr::deref(lid)), Base::Superglobal(ref expr) => { state.call_builtin(hack::Builtin::GetSuperglobal, [expr.clone()]) } Base::Value(ref expr) => state.fb.write_expr_stmt(expr.clone()), } } fn store(&self, state: &mut FuncState<'_, '_, '_>, value: Expr) -> Result { use textual::Const; match *self { Base::Field { base, prop: Expr::Const(Const::String(ref key)), op: PropOp::NullThrows, } => state.store_mixed(Expr::field(base, Ty::unknown(), key.clone()), value)?, Base::Field { base, ref prop, op } => { let null_safe = match op { PropOp::NullThrows => Const::False, PropOp::NullSafe => Const::True, }; state.call_builtin( hack::Builtin::HackPropSet, (base, prop.clone(), Expr::Const(null_safe), value), )?; } Base::Local(lid) => state.store_mixed(Expr::deref(lid), value)?, Base::Superglobal(ref expr) => { state.call_builtin(hack::Builtin::SetSuperglobal, (expr.clone(), value))?; } Base::Value(_) => { // This is something like `foo()[2] = 3`. We don't have // something to write back into so just ignore it. } } Ok(()) } } enum Pending { /// No operation pending. This should only ever be a transient state while /// we're consuming a previous one. None, /// We have a base with no array or property accessess yet. Since we have a /// MemberOp we know this will be replaced before we're done. Base(Base), /// We're currently processing a sequence of array accesses ending with an /// append. ArrayAppend { base: Base, dim: Vec<Expr> }, /// We're currently processing a sequence of array accesses. ArrayGet { base: Base, dim: Vec<Expr> }, } impl Pending { /// Read the current pending operation and return the value it represents. fn read(&self, state: &mut FuncState<'_, '_, '_>) -> Result<Sid> { match self { Pending::None => unreachable!(), Pending::Base(base) => base.load(state), Pending::ArrayAppend { .. } => { bail!("Cannot use [] with vecs for reading in an lvalue context"); } Pending::ArrayGet { base, dim } => { let base_value = base.load(state)?; let params = std::iter::once(base_value.into()) .chain(dim.iter().cloned()) .collect_vec(); state.call_builtin(hack::Builtin::HackArrayGet, params) } } } /// Write a value to the access this represents. fn write(self, state: &mut FuncState<'_, '_, '_>, src: Sid) -> Result { match self { Pending::None => unreachable!(), Pending::Base(base) => base.store(state, src.into())?, Pending::ArrayAppend { base, dim } => { let base_value = base.load(state)?; let params = std::iter::once(base_value.into()) .chain(dim.into_iter()) .chain(std::iter::once(src.into())) .collect_vec(); let base_value = state.call_builtin(hack::Builtin::HackArrayCowAppend, params)?; base.store(state, base_value.into())?; } Pending::ArrayGet { base, dim } => { let base_value = base.load(state)?; let params = std::iter::once(base_value.into()) .chain(dim.into_iter()) .chain(std::iter::once(src.into())) .collect_vec(); let base_value = state.call_builtin(hack::Builtin::HackArrayCowSet, params)?; base.store(state, base_value.into())?; } } Ok(()) } } /// The member operation state machine. /// /// A member operation will consist of a call to write_base(), 0 or more calls /// to write_entry(), and a call to finish(). /// struct MemberOpEmitter<'a, 'b, 'c, 'd, L, O> where L: Iterator<Item = LocalId>, O: Iterator<Item = ValueId>, { locals: L, operands: O, pending: Pending, state: &'a mut FuncState<'b, 'c, 'd>, } impl<'a, 'b, 'c, 'd, L, O> MemberOpEmitter<'a, 'b, 'c, 'd, L, O> where L: Iterator<Item = LocalId>, O: Iterator<Item = ValueId>, { fn new(state: &'a mut FuncState<'b, 'c, 'd>, locals: L, operands: O) -> Result<Self> { Ok(Self { locals, operands, pending: Pending::None, state, }) } fn write_base(&mut self, base_op: &BaseOp) -> Result { assert!(matches!(self.pending, Pending::None)); match *base_op { BaseOp::BaseC { .. } => { // Get base from value: foo()[k] let base = self.next_operand(); self.pending = Pending::Base(Base::Value(base)); } BaseOp::BaseGC { .. } => { // Get base from global name: $_SERVER[k] let src = self.next_operand(); self.pending = Pending::Base(Base::Superglobal(src)); } BaseOp::BaseH { loc: _ } => { // Get base from $this: $this[k] // Just pretend to be a BaseL w/ $this. let lid = LocalId::Named(self.state.strings.intern_str(special_idents::THIS)); self.pending = Pending::Base(Base::Local(lid)); } BaseOp::BaseL { mode: _, readonly: _, loc: _, } => { // Get base from local: $x[k] self.pending = Pending::Base(Base::Local(self.next_local())); } BaseOp::BaseSC { mode: _, readonly: _, loc: _, } => { // Get base from static property: $x::{$y}[k] // TODO: Is this even possible in Hack anymore? let prop = self.next_operand(); let base = self.next_operand(); self.pending = Pending::Base(Base::Value(base)); self.push_prop_dim(prop, PropOp::NullThrows)?; } BaseOp::BaseST { mode: _, readonly: _, loc: _, prop, } => { // Get base from static property with known key: $x::$y[k] // We treat C::$x the same as `get_static(C)->x`. let base = self.next_operand(); let key = { let key = self.state.strings.lookup_bytes(prop.id); crate::util::escaped_string(&key) }; self.pending = Pending::Base(Base::Value(base)); self.push_prop_dim(key.into(), PropOp::NullThrows)?; } } Ok(()) } fn write_entry(&mut self, key: &MemberKey) -> Result { match *key { MemberKey::EC => { // $a[foo()] let key = self.next_operand(); self.push_array_dim(key)?; } MemberKey::EI(i) => { // $a[3] let idx = self.state.call_builtin(hack::Builtin::Int, [i])?; self.push_array_dim(idx.into())?; } MemberKey::EL => { // $a[$b] let key = self.next_local(); let key = self.state.load_mixed(Expr::deref(key))?; self.push_array_dim(key.into())?; } MemberKey::ET(s) => { // $a["hello"] let key = { let key = self.state.strings.lookup_bytes(s); crate::util::escaped_string(&key) }; let key = self.state.call_builtin(hack::Builtin::String, [key])?; self.push_array_dim(key.into())?; } MemberKey::PC => { // $a->{foo()} let key = self.next_operand(); self.push_prop_dim(key, PropOp::NullThrows)?; } MemberKey::PL => { // $a->{$b} let key = self.next_local(); let key = self.state.load_mixed(Expr::deref(key))?; self.push_prop_dim(key.into(), PropOp::NullThrows)?; } MemberKey::PT(prop) => { // $a->hello let key = { let key = self.state.strings.lookup_bytes(prop.id); crate::util::escaped_string(&key) }; self.push_prop_dim(key.into(), PropOp::NullThrows)?; } MemberKey::QT(prop) => { // $a?->hello let key = { let key = self.state.strings.lookup_bytes(prop.id); crate::util::escaped_string(&key) }; self.push_prop_dim(key.into(), PropOp::NullSafe)?; } MemberKey::W => { // $a[] self.push_array_append()?; } } Ok(()) } fn finish(mut self, final_op: &FinalOp) -> Result<Sid> { use textual::Const; let key = final_op.key().unwrap(); self.write_entry(key)?; let value: Sid = match *final_op { FinalOp::IncDecM { inc_dec_op, .. } => { let pre = self.pending.read(self.state)?; let op = match inc_dec_op { ir::IncDecOp::PreInc | ir::IncDecOp::PostInc => hack::Hhbc::Add, ir::IncDecOp::PreDec | ir::IncDecOp::PostDec => hack::Hhbc::Sub, _ => unreachable!(), }; let incr = hack::expr_builtin(hack::Builtin::Int, [Expr::Const(Const::Int(1))]); let post = self .state .call_builtin(hack::Builtin::Hhbc(op), (pre, incr))?; self.pending.write(self.state, post)?; match inc_dec_op { ir::IncDecOp::PreInc | ir::IncDecOp::PreDec => post, ir::IncDecOp::PostInc | ir::IncDecOp::PostDec => pre, _ => unreachable!(), } } FinalOp::QueryM { query_m_op, .. } => match query_m_op { QueryMOp::CGet | QueryMOp::CGetQuiet => self.pending.read(self.state)?, QueryMOp::Isset => { let value = self.pending.read(self.state)?; self.state .call_builtin(hack::Builtin::Hhbc(hack::Hhbc::IsTypeNull), [value])? } QueryMOp::InOut => textual_todo! { todo!(); }, _ => unreachable!(), }, FinalOp::SetM { .. } => { let src = self.next_operand(); let src = self.state.fb.write_expr_stmt(src)?; self.pending.write(self.state, src)?; src } FinalOp::SetRangeM { .. } => unreachable!(), FinalOp::SetOpM { ref key, .. } => textual_todo! { match *key { MemberKey::EC => { self.next_operand(); } MemberKey::EI(_) => { } MemberKey::EL => { let _ = self.locals.next(); } MemberKey::ET(_) => { } MemberKey::PC => { } MemberKey::PL => { } MemberKey::PT(_) => { } MemberKey::QT(_) => { } MemberKey::W => { } } self.next_operand(); self.state.write_todo("SetOpM")? }, FinalOp::UnsetM { ref key, .. } => textual_todo! { match *key { MemberKey::EC => { self.next_operand(); } MemberKey::EI(_) => { } MemberKey::EL => { let _ = self.locals.next(); } MemberKey::ET(_) => { } MemberKey::PC => { } MemberKey::PL => { } MemberKey::PT(_) => { } MemberKey::QT(_) => { } MemberKey::W => { } } self.state.write_todo("UnsetM")? }, }; assert!(self.locals.next().is_none()); assert!(self.operands.next().is_none()); Ok(value) } fn push_array_dim(&mut self, key: Expr) -> Result { let pending = std::mem::replace(&mut self.pending, Pending::None); let (base, dim) = match pending { Pending::None => unreachable!(), Pending::Base(base) => (base, vec![key]), Pending::ArrayAppend { .. } => { bail!("Cannot use [] with vecs for reading in an lvalue context") } Pending::ArrayGet { base, mut dim } => { dim.push(key); (base, dim) } }; self.pending = Pending::ArrayGet { base, dim }; Ok(()) } fn push_array_append(&mut self) -> Result { let pending = std::mem::replace(&mut self.pending, Pending::None); let (base, dim) = match pending { Pending::None => unreachable!(), Pending::Base(base) => (base, vec![]), Pending::ArrayAppend { .. } => { bail!("Cannot use [] with vecs for reading in an lvalue context") } Pending::ArrayGet { base, dim } => (base, dim), }; self.pending = Pending::ArrayAppend { base, dim }; Ok(()) } fn push_prop_dim(&mut self, key: Expr, op: PropOp) -> Result { let pending = std::mem::replace(&mut self.pending, Pending::None); let (base, prop, op) = match pending { Pending::None => unreachable!(), Pending::Base(base) => { let base = base.load(self.state)?; (base, key, op) } Pending::ArrayAppend { .. } => { bail!("Cannot use [] with vecs for reading in an lvalue context") } Pending::ArrayGet { .. } => { let base = pending.read(self.state)?.into(); (base, key, op) } }; self.pending = Pending::Base(Base::Field { base, prop, op }); Ok(()) } fn next_operand(&mut self) -> Expr { self.state.lookup_vid(self.operands.next().unwrap()) } fn next_local(&mut self) -> LocalId { self.locals.next().unwrap() } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/textual/state.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::sync::Arc; use ir::StringInterner; pub(crate) struct UnitState { pub(crate) strings: Arc<StringInterner>, } impl UnitState { pub(crate) fn new(strings: Arc<StringInterner>) -> Self { Self { strings } } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/textual/textual.rs
#![allow(dead_code)] // Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. //! This is a structural version of the Textual language - it should have //! basically no business logic and just provides a type-safe way to write //! Textual. use std::borrow::Cow; use std::fmt; use std::sync::Arc; use anyhow::Error; use ascii::AsciiString; use hash::HashMap; use hash::HashSet; use ir::func::SrcLoc; use ir::BlockId; use ir::FloatBits; use ir::LocalId; use ir::StringInterner; use itertools::Itertools; use newtype::newtype_int; use strum::EnumProperty; use crate::mangle::FunctionName; use crate::mangle::GlobalName; use crate::mangle::Intrinsic; use crate::mangle::TypeName; pub(crate) const INDENT: &str = " "; pub(crate) const VARIADIC: &str = ".variadic"; type Result<T = (), E = Error> = std::result::Result<T, E>; pub(crate) struct TextualFile<'a> { w: &'a mut dyn std::io::Write, strings: Arc<StringInterner>, pub(crate) internal_functions: HashSet<FunctionName>, pub(crate) called_functions: HashSet<FunctionName>, pub(crate) internal_globals: HashMap<GlobalName, Ty>, pub(crate) referenced_globals: HashSet<GlobalName>, pub(crate) curry_tys: HashSet<CurryTy>, } impl<'a> TextualFile<'a> { pub(crate) fn new(w: &'a mut dyn std::io::Write, strings: Arc<StringInterner>) -> Self { TextualFile { w, strings, internal_functions: Default::default(), called_functions: Default::default(), internal_globals: Default::default(), referenced_globals: Default::default(), curry_tys: Default::default(), } } fn register_called_function(&mut self, target: &FunctionName) { if !target.contains_unknown() && !self.called_functions.contains(target) { self.called_functions.insert(target.clone()); } } pub(crate) fn debug_separator(&mut self) -> Result { writeln!(self.w)?; Ok(()) } pub(crate) fn declare_function( &mut self, name: &FunctionName, attributes: &FuncAttributes, tys: &[Ty], ret_ty: &Ty, ) -> Result { write!(self.w, "declare ")?; if attributes.is_final { write!(self.w, ".final ")?; } if attributes.is_async { write!(self.w, ".async ")?; } write!(self.w, "{}(", name.display(&self.strings))?; // TODO: For now textual can't handle a mix of types with a trailing // ellipsis. if tys.contains(&Ty::Ellipsis) { write!(self.w, "...")?; } else { let mut sep = ""; for ty in tys { write!(self.w, "{sep}{}", ty.display(&self.strings))?; sep = ", "; } } writeln!(self.w, "): {}", ret_ty.display(&self.strings))?; Ok(()) } #[allow(dead_code)] pub(crate) fn define_global(&mut self, name: GlobalName, ty: Ty) { self.internal_globals.insert(name, ty); } fn declare_unknown_function(&mut self, name: &FunctionName) -> Result { writeln!( self.w, "declare {name}(...): *HackMixed", name = name.display(&self.strings) )?; Ok(()) } fn declare_unknown_global(&mut self, name: &GlobalName) -> Result { writeln!( self.w, "global {name} : {ty}", name = name.display(&self.strings), ty = Ty::SpecialPtr(SpecialTy::Mixed).display(&self.strings) )?; Ok(()) } pub(crate) fn define_function<R>( &mut self, name: &FunctionName, loc: Option<&SrcLoc>, attributes: &FuncAttributes, params: &[Param<'_>], ret_ty: &Ty, locals: &[(LocalId, &Ty)], body: impl FnOnce(&mut FuncBuilder<'_, '_>) -> Result<R>, ) -> Result<R> { if !self.internal_functions.contains(name) { self.internal_functions.insert(name.clone()); } if let Some(loc) = loc { self.write_full_loc(loc)?; } write!(self.w, "define ")?; if attributes.is_final { write!(self.w, ".final ")?; } if attributes.is_async { write!(self.w, ".async ")?; } if attributes.is_curry { write!(self.w, ".curry ")?; } write!(self.w, "{}(", name.display(&self.strings))?; let mut sep = ""; for param in params { write!(self.w, "{sep}{name}: ", name = param.name,)?; if let Some(attrs) = param.attr.as_ref() { for attr in attrs.iter() { write!(self.w, "{attr} ")?; } } write!(self.w, "{ty}", ty = param.ty.display(&self.strings))?; sep = ", "; } writeln!(self.w, ") : {} {{", ret_ty.display(&self.strings))?; if !locals.is_empty() { let mut sep = ""; write!(self.w, "local ")?; for (lid, ty) in locals { write!( self.w, "{sep}{name}: {ty}", name = FmtLid(&self.strings, *lid), ty = ty.display(&self.strings) )?; sep = ", "; } writeln!(self.w)?; } let mut writer = FuncBuilder { cur_loc: loc.cloned(), next_id: Sid::from_usize(0), txf: self, cache: VarCache::default(), }; writer.write_label(BlockId::from_usize(0), &[])?; let result = body(&mut writer)?; writeln!(self.w, "}}")?; writeln!(self.w)?; Ok(result) } fn write_metadata<'s>( &mut self, metadata: impl Iterator<Item = (&'s str, &'s Const)>, ) -> Result { for (k, v) in metadata { // Special case - for a false value just emit nothing. if matches!(v, Const::False) { continue; } self.w.write_all(b".")?; self.w.write_all(k.as_bytes())?; // Special case - for a true value just emit the key. if !matches!(v, Const::True) { self.w.write_all(b"=")?; write!(self.w, "{}", FmtConst(v))?; } self.w.write_all(b" ")?; } Ok(()) } pub(crate) fn define_type<'s>( &mut self, name: &TypeName, src_loc: Option<&SrcLoc>, extends: impl Iterator<Item = &'s TypeName>, fields: impl Iterator<Item = Field<'s>>, metadata: impl Iterator<Item = (&'s str, &'s Const)>, ) -> Result { if let Some(src_loc) = src_loc { self.write_full_loc(src_loc)?; } write!(self.w, "type {}", name.display(&self.strings))?; let mut sep = " extends"; for base in extends { write!(self.w, "{sep} {}", base.display(&self.strings))?; sep = ","; } write!(self.w, " = ")?; self.write_metadata(metadata)?; write!(self.w, "{{")?; let mut sep = "\n"; for f in fields { for comment in &f.comments { writeln!(self.w, "{sep}{INDENT}// {comment}")?; sep = ""; } write!( self.w, "{sep}{INDENT}{name}: {vis} ", name = f.name, vis = f.visibility.decl() )?; for attr in &f.attributes { write!(self.w, "{} ", attr.display(&self.strings))?; } write!(self.w, "{ty}", ty = f.ty.display(&self.strings))?; sep = ";\n"; } writeln!(self.w, "\n}}")?; writeln!(self.w)?; Ok(()) } pub(crate) fn set_attribute(&mut self, attr: FileAttribute) -> Result { match attr { FileAttribute::SourceLanguage(lang) => { writeln!(self.w, ".source_language = \"{lang}\"")?; } } Ok(()) } pub(crate) fn write_comment(&mut self, msg: &str) -> Result { writeln!(self.w, "// {msg}")?; Ok(()) } pub(crate) fn write_epilogue<T: Eq + std::hash::Hash + Copy>( &mut self, builtins: &HashMap<FunctionName, T>, ) -> Result<HashSet<T>> { let strings = &Arc::clone(&self.strings); if !self.internal_globals.is_empty() { self.write_comment("----- GLOBALS -----")?; for (name, ty) in self .internal_globals .iter() .sorted_by(|(n1, _), (n2, _)| n1.cmp(n2, strings)) { writeln!( self.w, "global {name} : {ty}", name = name.display(strings), ty = ty.display(strings) )?; } self.debug_separator()?; } if !self.curry_tys.is_empty() { self.write_comment("----- CURRIES -----")?; let curry_tys = std::mem::take(&mut self.curry_tys); for curry in curry_tys.into_iter() { self.write_curry_definition(curry)?; } self.debug_separator()?; } let (builtins, mut non_builtin_fns): (HashSet<T>, Vec<FunctionName>) = (&self.called_functions - &self.internal_functions) .into_iter() .partition_map(|f| match builtins.get(&f as &FunctionName) { Some(b) => itertools::Either::Left(b), None => itertools::Either::Right(f), }); non_builtin_fns.sort_by(|a, b| a.cmp(b, strings)); let referenced_globals = &self.referenced_globals - &self.internal_globals.keys().cloned().collect(); if !non_builtin_fns.is_empty() || !referenced_globals.is_empty() { self.write_comment("----- EXTERNALS -----")?; for name in non_builtin_fns { self.declare_unknown_function(&name)?; } for name in referenced_globals { self.declare_unknown_global(&name)?; } self.debug_separator()?; } Ok(builtins) } fn write_curry_definition(&mut self, curry: CurryTy) -> Result { let curry_ty = curry.ty_name(); let mut fields = Vec::new(); if curry.virtual_call { let FunctionName::Method(captured_this_ty, _) = &curry.name else { unreachable!(); }; fields.push(Field { name: "this".into(), ty: Ty::named_type_ptr(captured_this_ty.clone()).into(), visibility: Visibility::Private, attributes: Default::default(), comments: Default::default(), }); } for (idx, ty) in curry.arg_tys.iter().enumerate() { fields.push(Field { name: format!("arg{idx}").into(), ty: ty.into(), visibility: Visibility::Private, attributes: Default::default(), comments: Default::default(), }); } let metadata_class: Const = "class".into(); let metadata_false: Const = false.into(); let metadata_true: Const = true.into(); let metadata = vec![ ("kind", &metadata_class), ("static", &metadata_false), ("final", &metadata_true), ]; self.define_type( &curry_ty, None, std::iter::empty(), fields.into_iter(), metadata.into_iter(), )?; const THIS_NAME: &str = "this"; const VARARGS_NAME: &str = "args"; let this_ty = Ty::Type(curry_ty.clone()); let this_ty_ptr = Ty::named_type_ptr(curry_ty.clone()); let args_ty = Ty::SpecialPtr(SpecialTy::Vec); let params = vec![ // ignored 'this' parameter Param { name: THIS_NAME.into(), attr: None, ty: (&this_ty_ptr).into(), }, Param { name: VARARGS_NAME.into(), attr: Some(vec![VARIADIC].into_boxed_slice()), ty: (&args_ty).into(), }, ]; let ret_ty = Ty::mixed_ptr(); let method = FunctionName::Intrinsic(Intrinsic::Invoke(curry_ty)); let attrs = FuncAttributes { is_async: false, is_curry: true, is_final: true, }; self.define_function(&method, None, &attrs, &params, &ret_ty, &[], |fb| { let this_id = fb.txf.strings.intern_str(THIS_NAME); let this = fb.load(&this_ty_ptr, Expr::deref(LocalId::Named(this_id)))?; let mut args = Vec::new(); for (idx, ty) in curry.arg_tys.iter().enumerate() { let arg = fb.load(ty, Expr::field(this, this_ty.clone(), format!("arg{idx}")))?; args.push(arg); } use crate::hack; let varargs_id = fb.txf.strings.intern_str(VARARGS_NAME); let varargs = fb.load(&args_ty, Expr::deref(LocalId::Named(varargs_id)))?; args.push(hack::call_builtin(fb, hack::Builtin::SilSplat, [varargs])?); let result = if curry.virtual_call { let captured_this_ty = match &curry.name { FunctionName::Method(captured_this_ty, _) => captured_this_ty, _ => { unreachable!(); } }; let captured_this = fb.load( &Ty::named_type_ptr(captured_this_ty.clone()), Expr::field(this, this_ty.clone(), "this"), )?; fb.call_virtual(&curry.name, captured_this.into(), args)? } else { fb.call_static(&curry.name, Expr::null(), args)? }; fb.ret(result)?; Ok(()) })?; Ok(()) } fn write_full_loc(&mut self, src_loc: &SrcLoc) -> Result { let filename = self.strings.lookup_bstr(src_loc.filename.0); writeln!(self.w, "// .file \"{filename}\"")?; drop(filename); self.write_line_loc(src_loc)?; Ok(()) } fn write_line_loc(&mut self, src_loc: &SrcLoc) -> Result { writeln!(self.w, "// .line {}", src_loc.line_begin)?; Ok(()) } } #[derive(Debug, Default)] pub(crate) struct FuncAttributes { pub is_async: bool, pub is_curry: bool, pub is_final: bool, } #[derive(Debug, Hash, PartialEq, Eq)] pub(crate) struct CurryTy { name: FunctionName, virtual_call: bool, arg_tys: Box<[Ty]>, } impl CurryTy { fn ty_name(&self) -> TypeName { TypeName::Curry(Box::new(self.name.clone())) } fn ty(&self) -> Ty { Ty::Type(self.ty_name()) } } newtype_int!(Sid, u32, SidMap, SidSet); struct FmtBid(BlockId); impl fmt::Display for FmtBid { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "b{}", self.0.as_usize()) } } struct FmtLid<'a>(&'a StringInterner, LocalId); impl fmt::Display for FmtLid<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let FmtLid(strings, lid) = *self; match lid { LocalId::Named(id) => { write!(f, "{}", strings.lookup_bstr(id)) } LocalId::Unnamed(id) => { write!(f, "${}", id.as_usize()) } } } } struct FmtSid(Sid); impl fmt::Display for FmtSid { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let FmtSid(sid) = *self; write!(f, "n{}", sid.as_usize()) } } /// These are special types that could be expressed as Ptr(Box(String)) but are /// really common. #[derive(Copy, Debug, Clone, Hash, Eq, PartialEq, EnumProperty)] pub(crate) enum SpecialTy { #[strum(props(UserType = "HackArraykey"))] Arraykey, #[strum(props(UserType = "HackBool"))] Bool, #[strum(props(UserType = "HackDict"))] Dict, #[strum(props(UserType = "HackFloat"))] Float, #[strum(props(UserType = "HackInt"))] Int, #[strum(props(UserType = "HackKeyset"))] Keyset, #[strum(props(UserType = "HackMixed"))] Mixed, #[strum(props(UserType = "HackNum"))] Num, #[strum(props(UserType = "HackString"))] String, #[strum(props(UserType = "HackVec"))] Vec, } impl SpecialTy { fn user_type(&self) -> TypeName { TypeName::UnmangledRef(self.get_str("UserType").unwrap()) } } #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub(crate) enum Ty { Ellipsis, Float, Int, Noreturn, Ptr(Box<Ty>), SpecialPtr(SpecialTy), Special(SpecialTy), String, Type(TypeName), Unknown, Void, VoidPtr, } impl Ty { pub(crate) fn display<'r>(&'r self, strings: &'r StringInterner) -> impl fmt::Display + 'r { FmtTy(strings, self) } pub(crate) fn deref(&self) -> Ty { let Some(ty) = self.try_deref() else { panic!("Unable to deref {self:?}"); }; ty } pub(crate) fn try_deref(&self) -> Option<Ty> { match self { Ty::Ptr(box sub) => Some(sub.clone()), Ty::VoidPtr => Some(Ty::Void), Ty::SpecialPtr(special) => Some(Ty::Special(*special)), Ty::Float | Ty::Int | Ty::Noreturn | Ty::String | Ty::Special(_) | Ty::Type(_) | Ty::Unknown | Ty::Void | Ty::Ellipsis => None, } } pub(crate) fn mixed_ptr() -> Ty { Ty::SpecialPtr(SpecialTy::Mixed) } pub(crate) fn named_type_ptr(name: TypeName) -> Ty { Ty::Ptr(Box::new(Ty::Type(name))) } pub(crate) fn unknown() -> Ty { Ty::Unknown } } impl From<Ty> for std::borrow::Cow<'_, Ty> { fn from(ty: Ty) -> Self { Self::Owned(ty) } } impl<'a> From<&'a Ty> for std::borrow::Cow<'a, Ty> { fn from(ty: &'a Ty) -> Self { Self::Borrowed(ty) } } struct FmtTy<'a>(&'a StringInterner, &'a Ty); impl fmt::Display for FmtTy<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let FmtTy(strings, ty) = *self; match ty { Ty::Ellipsis => write!(f, "..."), Ty::Float => write!(f, "float"), Ty::Int => write!(f, "int"), Ty::Noreturn => f.write_str("noreturn"), Ty::Ptr(sub) => write!(f, "*{}", sub.display(strings)), Ty::SpecialPtr(special) => write!(f, "*{}", special.user_type().display(strings)), Ty::Special(special) => special.user_type().display(strings).fmt(f), Ty::String => write!(f, "*string"), Ty::Type(s) => s.display(strings).fmt(f), Ty::Unknown => f.write_str("?"), Ty::Void => f.write_str("void"), Ty::VoidPtr => f.write_str("*void"), } } } #[derive(Clone, Debug, Hash, Eq, PartialEq)] pub(crate) enum Var { Global(GlobalName), Local(LocalId), } impl Var { pub(crate) fn global(s: GlobalName) -> Self { Var::Global(s) } } impl From<LocalId> for Var { fn from(lid: LocalId) -> Var { Var::Local(lid) } } struct FmtVar<'a>(&'a StringInterner, &'a Var); impl fmt::Display for FmtVar<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let FmtVar(strings, var) = *self; match *var { Var::Global(ref s) => s.display(strings).fmt(f), Var::Local(lid) => FmtLid(strings, lid).fmt(f), } } } #[derive(Clone, Debug, Hash, Eq, PartialEq)] pub(crate) enum Const { False, Float(FloatBits), Int(i64), Null, String(AsciiString), True, } impl From<&'static str> for Const { fn from(s: &'static str) -> Self { Const::String(AsciiString::from_ascii(s).unwrap()) } } impl From<AsciiString> for Const { fn from(s: AsciiString) -> Self { Const::String(s) } } impl From<bool> for Const { fn from(v: bool) -> Self { if v { Const::True } else { Const::False } } } impl From<f64> for Const { fn from(f: f64) -> Self { Const::Float(f.into()) } } impl From<i64> for Const { fn from(i: i64) -> Self { Const::Int(i) } } struct FmtConst<'a>(&'a Const); impl fmt::Display for FmtConst<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let FmtConst(const_) = *self; match const_ { Const::False => f.write_str("false"), Const::Float(d) => write!(f, "{:?}", d.to_f64()), Const::Int(i) => i.fmt(f), Const::Null => f.write_str("null"), Const::String(ref s) => { // String should already be escaped... write!(f, "\"{}\"", s) } Const::True => f.write_str("true"), } } } #[derive(Clone, Debug, Hash, Eq, PartialEq)] pub(crate) enum Expr { /// __sil_allocate(\<ty\>) Alloc(Ty), /// foo(1, 2, 3) Call(FunctionName, Box<[Expr]>), /// 0, null, etc Const(Const), /// *Variable Deref(Box<Expr>), /// a.b Field(Box<Expr>, Ty, String), /// a[b] Index(Box<Expr>, Box<Expr>), /// __sil_instanceof(expr, \<ty\>) InstanceOf(Box<Expr>, Ty), Sid(Sid), Var(Var), } impl Expr { pub(crate) fn call(target: FunctionName, params: impl VarArgs) -> Expr { Expr::Call(target, params.into_exprs().into_boxed_slice()) } pub(crate) fn deref(v: impl Into<Expr>) -> Expr { Expr::Deref(Box::new(v.into())) } pub(crate) fn field(base: impl Into<Expr>, base_ty: Ty, name: impl Into<String>) -> Expr { let base = base.into(); let name = name.into(); Expr::Field(Box::new(base), base_ty, name) } #[allow(dead_code)] pub(crate) fn index(base: impl Into<Expr>, offset: impl Into<Expr>) -> Expr { let base = base.into(); let offset = offset.into(); Expr::Index(Box::new(base), Box::new(offset)) } pub(crate) fn null() -> Expr { Expr::Const(Const::Null) } pub(crate) fn ty(&self) -> Ty { match self { Expr::Sid(_) => Ty::mixed_ptr(), Expr::Const(Const::Null) => Ty::VoidPtr, _ => todo!("EXPR: {self:?}"), } } } impl<T: Into<Const>> From<T> for Expr { fn from(value: T) -> Self { Expr::Const(value.into()) } } impl From<Sid> for Expr { fn from(sid: Sid) -> Self { Expr::Sid(sid) } } impl From<Var> for Expr { fn from(var: Var) -> Self { Expr::Var(var) } } impl From<LocalId> for Expr { fn from(lid: LocalId) -> Expr { Expr::Var(lid.into()) } } pub(crate) trait VarArgs { fn into_exprs(self) -> Vec<Expr>; } impl<T> VarArgs for &[T] where T: Into<Expr> + Copy, { fn into_exprs(self) -> Vec<Expr> { self.iter().copied().map_into().collect_vec() } } impl VarArgs for () { fn into_exprs(self) -> Vec<Expr> { Vec::new() } } impl<T> VarArgs for [T; 1] where T: Into<Expr>, { fn into_exprs(self) -> Vec<Expr> { let [a] = self; vec![a.into()] } } impl<T> VarArgs for [T; 2] where T: Into<Expr>, { fn into_exprs(self) -> Vec<Expr> { let [a, b] = self; vec![a.into(), b.into()] } } impl<T> VarArgs for [T; 3] where T: Into<Expr>, { fn into_exprs(self) -> Vec<Expr> { let [a, b, c] = self; vec![a.into(), b.into(), c.into()] } } impl<T> VarArgs for [T; 4] where T: Into<Expr>, { fn into_exprs(self) -> Vec<Expr> { let [a, b, c, d] = self; vec![a.into(), b.into(), c.into(), d.into()] } } impl<T> VarArgs for Vec<T> where T: Into<Expr>, { fn into_exprs(self) -> Vec<Expr> { self.into_iter().map_into().collect_vec() } } impl<T> VarArgs for Box<[T]> where T: Into<Expr>, { fn into_exprs(self) -> Vec<Expr> { Vec::from(self).into_exprs() } } impl<P1, P2> VarArgs for (P1, P2) where P1: Into<Expr>, P2: Into<Expr>, { fn into_exprs(self) -> Vec<Expr> { vec![self.0.into(), self.1.into()] } } impl<P1, P2, P3> VarArgs for (P1, P2, P3) where P1: Into<Expr>, P2: Into<Expr>, P3: Into<Expr>, { fn into_exprs(self) -> Vec<Expr> { vec![self.0.into(), self.1.into(), self.2.into()] } } impl<P1, P2, P3, P4> VarArgs for (P1, P2, P3, P4) where P1: Into<Expr>, P2: Into<Expr>, P3: Into<Expr>, P4: Into<Expr>, { fn into_exprs(self) -> Vec<Expr> { vec![self.0.into(), self.1.into(), self.2.into(), self.3.into()] } } impl<T, I, O, F> VarArgs for std::iter::Map<I, F> where T: Into<Expr>, I: Iterator<Item = O>, F: FnMut(O) -> T, { fn into_exprs(self) -> Vec<Expr> { self.map_into().collect_vec() } } pub(crate) enum FileAttribute { SourceLanguage(String), } pub(crate) struct FuncBuilder<'a, 'b> { cur_loc: Option<SrcLoc>, next_id: Sid, pub(crate) txf: &'a mut TextualFile<'b>, cache: VarCache, } impl FuncBuilder<'_, '_> { pub fn alloc_sid(&mut self) -> Sid { let id = self.next_id; self.next_id = Sid::from_usize(id.as_usize() + 1); id } } impl FuncBuilder<'_, '_> { pub(crate) fn jmp(&mut self, targets: &[BlockId], params: impl VarArgs) -> Result { assert!(!targets.is_empty()); let params = params.into_exprs(); write!(self.txf.w, "{INDENT}jmp ")?; let mut sep1 = ""; for &target in targets { write!(self.txf.w, "{sep1}{}", FmtBid(target))?; sep1 = ", "; if !params.is_empty() { write!(self.txf.w, "(")?; let mut sep2 = ""; for param in params.iter() { self.txf.w.write_all(sep2.as_bytes())?; self.write_expr(param)?; sep2 = ", "; } write!(self.txf.w, ")")?; } } writeln!(self.txf.w)?; Ok(()) } pub(crate) fn write_exception_handler(&mut self, target: BlockId) -> Result { writeln!(self.txf.w, "{INDENT}.handlers {}", FmtBid(target))?; Ok(()) } fn write_expr(&mut self, expr: &Expr) -> Result { match *expr { Expr::Alloc(ref ty) => write!( self.txf.w, "__sil_allocate(<{}>)", ty.display(&self.txf.strings) )?, Expr::Call(ref target, ref params) => { self.write_call_expr(target, params)?; } Expr::Const(ref c) => write!(self.txf.w, "{}", FmtConst(c))?, Expr::Deref(ref var) => { self.txf.w.write_all(b"&")?; self.write_expr(var)?; } Expr::Field(ref base, ref ty, ref name) => { self.write_expr(base)?; write!(self.txf.w, ".{}.{name}", ty.display(&self.txf.strings))?; } Expr::Index(ref base, ref offset) => { self.write_expr(base)?; self.txf.w.write_all(b"[")?; self.write_expr(offset)?; self.txf.w.write_all(b"]")?; } Expr::InstanceOf(ref expr, ref ty) => { write!(self.txf.w, "__sil_instanceof(")?; self.write_expr(expr)?; write!(self.txf.w, ", <{}>)", ty.display(&self.txf.strings))?; } Expr::Sid(sid) => write!(self.txf.w, "{}", FmtSid(sid))?, Expr::Var(ref var) => { match var { Var::Global(s) => { if !self.txf.referenced_globals.contains(s) { self.txf.referenced_globals.insert(s.to_owned()); } } Var::Local(_) => {} } write!(self.txf.w, "{}", FmtVar(&self.txf.strings, var))? } } Ok(()) } pub(crate) fn write_expr_stmt(&mut self, expr: impl Into<Expr>) -> Result<Sid> { let expr = expr.into(); match expr { Expr::Alloc(_) | Expr::InstanceOf(..) | Expr::Const(_) | Expr::Deref(_) | Expr::Field(..) | Expr::Index(..) | Expr::Var(..) => { let sid = self.alloc_sid(); write!(self.txf.w, "{INDENT}{} = ", FmtSid(sid))?; self.write_expr(&expr)?; writeln!(self.txf.w)?; Ok(sid) } Expr::Call(target, params) => self.call(&target, params), Expr::Sid(sid) => Ok(sid), } } pub(crate) fn write_label(&mut self, bid: BlockId, params: &[Sid]) -> Result { self.cache.clear(); if params.is_empty() { writeln!(self.txf.w, "#{}:", FmtBid(bid))?; } else { write!(self.txf.w, "#{}(", FmtBid(bid))?; let mut sep = ""; for sid in params { write!(self.txf.w, "{sep}{}: *HackMixed", FmtSid(*sid))?; sep = ", "; } writeln!(self.txf.w, "):")?; } Ok(()) } /// A curry boxes up some parameters and returns an invokable. This has to /// be an intrinsic so we don't end up a ton of little duplicate classes. /// /// It's usually used for function pointers or meth_callers: /// /// `foo<>` turns into `AllocCurry("<$root>", "foo", null, [])`. /// `C::foo<>` turns into `AllocCurry("<C$static>", "foo", static_this, [])`. /// `$x->foo<>` turns into `AllocCurry("<C>", "foo", $x, [])`. /// /// Note that it's important that when the curry is invoked it replaces the /// callee's `this` with its own stored `this`. /// /// Curry can also be used for partial apply: /// /// x = AllocCurry("<$root>", "foo", null, [1, 2]) /// x(3, 4) /// /// would be the same as: /// /// foo(1, 2, 3, 4) /// /// If `this` is Some(_) then the curry will be a virtual call. /// pub(crate) fn write_alloc_curry( &mut self, name: FunctionName, this: Option<Expr>, args: impl VarArgs, ) -> Result<Sid> { let args = args.into_exprs(); let curry_ty = CurryTy { name: name.clone(), virtual_call: this.is_some(), arg_tys: args.iter().map(|expr| expr.ty()).collect(), }; let ty = curry_ty.ty(); self.txf.curry_tys.insert(curry_ty); let obj = self.write_expr_stmt(Expr::Alloc(ty.clone()))?; if let Some(this) = this { let FunctionName::Method(captured_this_ty, _) = &name else { unreachable!(); }; self.store( Expr::Field(Box::new(obj.into()), ty.clone(), "this".to_string()), this, &Ty::named_type_ptr(captured_this_ty.clone()), )?; } for (idx, arg) in args.into_iter().enumerate() { let field_ty = arg.ty(); self.store( Expr::field(obj, ty.clone(), format!("arg{idx}")), arg, &field_ty, )?; } Ok(obj) } /// Call the target as a static call (without virtual dispatch). pub(crate) fn call_static( &mut self, target: &FunctionName, this: Expr, params: impl VarArgs, ) -> Result<Sid> { self.txf.register_called_function(target); let dst = self.alloc_sid(); write!( self.txf.w, "{INDENT}{dst} = {target}(", dst = FmtSid(dst), target = target.display(&self.txf.strings) )?; self.write_expr(&this)?; let params = params.into_exprs(); for param in params { self.txf.w.write_all(b", ")?; self.write_expr(&param)?; } writeln!(self.txf.w, ")")?; Ok(dst) } /// Call the target as a virtual call. pub(crate) fn call_virtual( &mut self, target: &FunctionName, this: Expr, params: impl VarArgs, ) -> Result<Sid> { self.txf.register_called_function(target); let dst = self.alloc_sid(); write!(self.txf.w, "{INDENT}{dst} = ", dst = FmtSid(dst),)?; self.write_expr(&this)?; write!(self.txf.w, ".{}(", target.display(&self.txf.strings))?; let params = params.into_exprs(); let mut sep = ""; for param in params { self.txf.w.write_all(sep.as_bytes())?; self.write_expr(&param)?; sep = ", "; } writeln!(self.txf.w, ")")?; Ok(dst) } fn write_call_expr(&mut self, target: &FunctionName, params: &[Expr]) -> Result { self.txf.register_called_function(target); write!(self.txf.w, "{}(", target.display(&self.txf.strings))?; let mut sep = ""; for param in params.iter() { self.txf.w.write_all(sep.as_bytes())?; self.write_expr(param)?; sep = ", "; } write!(self.txf.w, ")")?; // Treat any call as if it can modify memory. for param in params.iter() { self.cache.clear_expr(param); } Ok(()) } pub(crate) fn call(&mut self, target: &FunctionName, params: impl VarArgs) -> Result<Sid> { let params = params.into_exprs(); let dst = self.alloc_sid(); write!(self.txf.w, "{INDENT}{dst} = ", dst = FmtSid(dst),)?; self.write_call_expr(target, &params)?; writeln!(self.txf.w)?; Ok(dst) } pub(crate) fn comment(&mut self, msg: &str) -> Result<()> { writeln!(self.txf.w, "// {msg}")?; Ok(()) } pub(crate) fn lazy_class_initialize(&mut self, ty: &Ty) -> Result<Sid> { let dst = self.alloc_sid(); let strings = &self.txf.strings; writeln!( self.txf.w, "{INDENT}{dst} = __sil_lazy_class_initialize(<{ty}>)", dst = FmtSid(dst), ty = ty.display(strings), )?; Ok(dst) } pub(crate) fn load(&mut self, ty: &Ty, src: impl Into<Expr>) -> Result<Sid> { let src = src.into(); // Technically the load should include the type because you could have // two loads of the same expression to two different types. I doubt that // it matters in reality. Ok(if let Some(sid) = self.cache.lookup(&src) { sid } else { let dst = self.alloc_sid(); write!( self.txf.w, "{INDENT}{dst}: {ty} = load ", dst = FmtSid(dst), ty = ty.display(&self.txf.strings), )?; self.write_expr(&src)?; writeln!(self.txf.w)?; self.cache.load(&src, dst); dst }) } // Terminate this branch if `expr` is false. pub(crate) fn prune(&mut self, expr: impl Into<Expr>) -> Result { let expr = expr.into(); write!(self.txf.w, "{INDENT}prune ")?; self.write_expr(&expr)?; writeln!(self.txf.w)?; Ok(()) } // Terminate this branch if `expr` is true. pub(crate) fn prune_not(&mut self, expr: impl Into<Expr>) -> Result { let expr = expr.into(); write!(self.txf.w, "{INDENT}prune ! ")?; self.write_expr(&expr)?; writeln!(self.txf.w)?; Ok(()) } pub(crate) fn ret(&mut self, expr: impl Into<Expr>) -> Result { let expr = expr.into(); write!(self.txf.w, "{INDENT}ret ",)?; self.write_expr(&expr)?; writeln!(self.txf.w)?; Ok(()) } pub(crate) fn store( &mut self, dst: impl Into<Expr>, src: impl Into<Expr>, src_ty: &Ty, ) -> Result { let dst = dst.into(); let src = src.into(); write!(self.txf.w, "{INDENT}store ")?; self.write_expr(&dst)?; self.txf.w.write_all(b" <- ")?; self.write_expr(&src)?; writeln!(self.txf.w, ": {ty}", ty = src_ty.display(&self.txf.strings))?; self.cache.store(&dst, src); Ok(()) } pub(crate) fn unreachable(&mut self) -> Result { writeln!(self.txf.w, "{INDENT}unreachable")?; Ok(()) } pub(crate) fn write_loc(&mut self, src_loc: &SrcLoc) -> Result { if let Some(cur_loc) = self.cur_loc.as_ref() { if src_loc.filename != cur_loc.filename { self.txf.write_full_loc(src_loc)?; self.cur_loc = Some(src_loc.clone()); } else if src_loc.line_begin != cur_loc.line_begin { self.txf.write_line_loc(src_loc)?; self.cur_loc = Some(src_loc.clone()); } } else { self.txf.write_full_loc(src_loc)?; self.cur_loc = Some(src_loc.clone()); } Ok(()) } } #[derive(Default, Debug)] struct VarCache { cache: HashMap<Var, Sid>, } impl VarCache { fn clear(&mut self) { self.cache.clear(); } fn load(&mut self, src: &Expr, sid: Sid) { match src { Expr::Deref(box Expr::Var(var)) => { self.cache.insert(var.clone(), sid); } _ => {} } } fn clear_expr(&mut self, target: &Expr) { match target { Expr::Deref(box Expr::Var(var)) => { self.cache.remove(var); } _ => {} } } fn store(&mut self, target: &Expr, value: Expr) { match target { Expr::Deref(box Expr::Var(var)) => { // If we're storing into a local then clear it. match value { Expr::Sid(sid) => { // If we're storing a direct value then remember the // value for later. self.load(target, sid); } _ => { self.cache.remove(var); } } } _ => {} } } fn lookup(&self, expr: &Expr) -> Option<Sid> { match expr { Expr::Deref(box Expr::Var(var)) => self.cache.get(var).cloned(), _ => None, } } } #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] pub(crate) enum Visibility { Public, Private, Protected, } impl Visibility { fn decl(&self) -> &str { match self { Visibility::Public => ".public", Visibility::Private => ".private", Visibility::Protected => ".protected", } } } pub(crate) enum FieldAttribute { Unparameterized { name: TypeName, }, Parameterized { name: TypeName, parameters: Vec<String>, }, } impl FieldAttribute { fn name(&self) -> &TypeName { match self { Self::Unparameterized { name } | Self::Parameterized { name, .. } => name, } } fn display<'a>(&'a self, strings: &'a StringInterner) -> impl fmt::Display + 'a { struct D<'a> { attr: &'a FieldAttribute, strings: &'a StringInterner, } impl fmt::Display for D<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, ".{}", self.attr.name().display(self.strings))?; match self.attr { FieldAttribute::Unparameterized { .. } => {} FieldAttribute::Parameterized { name: _, parameters, } => { let mut i = parameters.iter(); let param = i.next().unwrap(); write!(f, "= \"{param}\"")?; for param in i { write!(f, ", \"{param}\"")?; } write!(f, " ")?; } } Ok(()) } } D { attr: self, strings, } } } pub(crate) struct Field<'a> { pub name: Cow<'a, str>, pub ty: Cow<'a, Ty>, pub visibility: Visibility, pub attributes: Vec<FieldAttribute>, pub comments: Vec<String>, } #[derive(Clone)] pub(crate) struct Param<'a> { pub name: Cow<'a, str>, pub attr: Option<Box<[&'a str]>>, pub ty: Cow<'a, Ty>, }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/textual/typed_value.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use hack::Builtin; use hack::Hhbc; use ir::ArrayKey; use ir::ClassId; use ir::StringInterner; use ir::TypedValue; use itertools::Itertools; use textual::Const; use textual::Expr; use crate::hack; use crate::textual; use crate::util; pub(crate) fn typed_value_expr(tv: &TypedValue, strings: &StringInterner) -> Expr { match *tv { TypedValue::Uninit => textual::Expr::null(), TypedValue::Int(n) => hack::expr_builtin(Builtin::Int, [Expr::Const(Const::Int(n))]), TypedValue::Bool(false) => hack::expr_builtin(Builtin::Bool, [Expr::Const(Const::False)]), TypedValue::Bool(true) => hack::expr_builtin(Builtin::Bool, [Expr::Const(Const::True)]), TypedValue::Float(f) => hack::expr_builtin(Builtin::Float, [Expr::Const(Const::Float(f))]), TypedValue::String(s) | TypedValue::LazyClass(ClassId { id: s }) => { let s = util::escaped_string(&strings.lookup_bytes(s)); hack::expr_builtin(Builtin::String, [Expr::Const(Const::String(s))]) } TypedValue::Null => textual::Expr::null(), TypedValue::Vec(ref v) => { let args: Vec<Expr> = v .iter() .map(|value| typed_value_expr(value, strings)) .collect_vec(); hack::expr_builtin(Builtin::Hhbc(Hhbc::NewVec), args) } TypedValue::Keyset(ir::KeysetValue(ref k)) => { let args: Vec<Expr> = k .iter() .map(|value| array_key_expr(value, strings)) .collect_vec(); hack::expr_builtin(Builtin::Hhbc(Hhbc::NewKeysetArray), args) } TypedValue::Dict(ir::DictValue(ref d)) => { let args = d .iter() .flat_map(|(k, v)| { let k = array_key_expr(k, strings); let v = typed_value_expr(v, strings); [k, v] }) .collect_vec(); hack::expr_builtin(Builtin::NewDict, args) } } } pub(crate) fn array_key_expr(ak: &ArrayKey, strings: &StringInterner) -> Expr { match *ak { ArrayKey::Int(n) => hack::expr_builtin(Builtin::Int, [Expr::Const(Const::Int(n))]), ArrayKey::String(s) | ArrayKey::LazyClass(ClassId { id: s }) => { let s = util::escaped_string(&strings.lookup_bytes(s)); hack::expr_builtin(Builtin::String, [Expr::Const(Const::String(s))]) } } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/textual/types.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use ir::BaseType; use ir::EnforceableType; use ir::StringInterner; use ir::TypeConstraintFlags; use crate::mangle::TypeName; use crate::textual; pub(crate) fn convert_ty(ty: &EnforceableType, strings: &StringInterner) -> textual::Ty { let mut base = convert_base(&ty.ty); let mut modifiers = ty.modifiers; // ExtendedHint does nothing interesting. modifiers -= TypeConstraintFlags::ExtendedHint; // DisplayNullable does nothing interesting. modifiers -= TypeConstraintFlags::DisplayNullable; // TypeVar doesn't add any interesting context. modifiers -= TypeConstraintFlags::TypeVar; // All textual boxed types are nullable. modifiers -= TypeConstraintFlags::Nullable; if modifiers.contains(TypeConstraintFlags::TypeConstant) { // A type constant is treated as a raw mixed. return textual::Ty::mixed_ptr(); } if modifiers != TypeConstraintFlags::NoFlags { textual_todo! { message = ("MODIFIERS: {modifiers:?}\n{}", ir::print::FmtEnforceableType(ty, strings) ), base = textual::Ty::Type(TypeName::UnmangledRef("TODO_NoFlags")); } } base } fn convert_base(ty: &BaseType) -> textual::Ty { match ty { BaseType::Arraykey => textual::Ty::SpecialPtr(textual::SpecialTy::Arraykey), BaseType::Bool => textual::Ty::SpecialPtr(textual::SpecialTy::Bool), BaseType::Class(cid) => textual::Ty::named_type_ptr(TypeName::Class(*cid)), BaseType::Classname => textual::Ty::named_type_ptr(TypeName::UnmangledRef("Classname")), BaseType::Dict => textual::Ty::SpecialPtr(textual::SpecialTy::Dict), BaseType::Float => textual::Ty::SpecialPtr(textual::SpecialTy::Float), BaseType::Int => textual::Ty::SpecialPtr(textual::SpecialTy::Int), BaseType::Keyset => textual::Ty::SpecialPtr(textual::SpecialTy::Keyset), BaseType::Null => textual::Ty::VoidPtr, BaseType::Num => textual::Ty::SpecialPtr(textual::SpecialTy::Num), BaseType::Resource => textual::Ty::named_type_ptr(TypeName::UnmangledRef("HackResource")), BaseType::String => textual::Ty::SpecialPtr(textual::SpecialTy::String), BaseType::Vec => textual::Ty::SpecialPtr(textual::SpecialTy::Vec), // Why VoidPtr? Because in Hack something returning `void` implicitly // returns a null. BaseType::Void => textual::Ty::VoidPtr, BaseType::AnyArray | BaseType::Darray | BaseType::Varray | BaseType::VarrayOrDarray | BaseType::VecOrDict => textual::Ty::named_type_ptr(TypeName::UnmangledRef("HackArray")), BaseType::Noreturn | BaseType::Nothing => textual::Ty::Noreturn, BaseType::Mixed | BaseType::None | BaseType::Nonnull | BaseType::This | BaseType::Typename => textual::Ty::mixed_ptr(), } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/textual/util.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::borrow::Cow; use ascii::AsciiChar; use ascii::AsciiString; pub fn escaped_string(input: &[u8]) -> AsciiString { let mut res = AsciiString::with_capacity(input.len()); for &ch in input { let code = match ch { b'\\' => AsciiChar::new('\\'), b'\n' => AsciiChar::new('n'), b'\r' => AsciiChar::new('r'), b'\t' => AsciiChar::new('t'), b'"' => { // \" doesn't work - emit \042 instead res.push(AsciiChar::BackSlash); res.push(AsciiChar::_0); res.push(AsciiChar::_4); res.push(AsciiChar::_2); continue; } _ if ch == b' ' || ch.is_ascii_graphic() => { res.push(AsciiChar::new(ch as char)); continue; } _ => { // \ooo res.push(AsciiChar::BackSlash); res.push(AsciiChar::new((b'0' + (ch >> 6)) as char)); res.push(AsciiChar::new((b'0' + ((ch >> 3) & 7)) as char)); res.push(AsciiChar::new((b'0' + (ch & 7)) as char)); continue; } }; res.push(AsciiChar::BackSlash); res.push(code); } res } // Make sure the input is a valid identifier. pub fn escaped_ident<'a>(input: Cow<'a, str>) -> Cow<'a, str> { // let ident = [%sedlex.regexp? (letter | Chars "_$"), Star (letter | digit | Chars "_$" | "::")] let mut it = input.chars(); let mut last_colon = false; let valid = it.next().map_or(true, |ch| { // Although first char can be '_' we use that to indicate an escaped // string so we need to tweak it. ch.is_ascii_alphabetic() || ch == '$' }) && it.all(|ch| match (ch, last_colon) { (':', _) => { last_colon = !last_colon; true } (_, true) => false, (ch, false) => ch.is_ascii_alphanumeric() || (ch == '$') || (ch == '_'), }); if !last_colon && valid { return input; } let mut out = String::with_capacity(input.len() * 3 / 2); out.push('_'); let mut last_colon = false; for ch in input.bytes() { if ch == b':' { if last_colon { out.push(':'); out.push(':'); } last_colon = !last_colon; continue; } if last_colon { out.push_str("_3a"); last_colon = false; } if ch.is_ascii_alphanumeric() || ch == b'$' { out.push(ch as char); } else { out.push('_'); if ch == b'_' { out.push('_'); } else { out.push(b"0123456789abcdef"[(ch >> 4) as usize] as char); out.push(b"0123456789abcdef"[(ch & 15) as usize] as char); } } } Cow::Owned(out) }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/textual/writer.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::path::Path; use std::sync::Arc; use anyhow::bail; use anyhow::Result; use hash::HashMap; use strum::IntoEnumIterator; use crate::decls; use crate::hack; use crate::mangle::FunctionName; use crate::state::UnitState; use crate::textual; use crate::textual::TextualFile; const UNIT_START_MARKER: &str = "TEXTUAL UNIT START"; const UNIT_END_MARKER: &str = "TEXTUAL UNIT END"; pub fn textual_writer( w: &mut dyn std::io::Write, path: &Path, unit: ir::Unit<'_>, no_builtins: bool, ) -> Result<()> { let mut txf = TextualFile::new(w, Arc::clone(&unit.strings)); let escaped_path = escaper::escape(path.display().to_string()); txf.write_comment(&format!("{UNIT_START_MARKER} {escaped_path}"))?; txf.set_attribute(textual::FileAttribute::SourceLanguage("hack".to_string()))?; txf.debug_separator()?; let mut state = UnitState::new(Arc::clone(&unit.strings)); check_fatal(path, unit.fatal.as_ref())?; for cls in unit.classes { crate::class::write_class(&mut txf, &mut state, cls)?; } for func in unit.functions { crate::func::write_function(&mut txf, &mut state, func)?; } use hack::Builtin; let all_builtins: HashMap<FunctionName, hack::Builtin> = hack::Builtin::iter() .map(|b| (FunctionName::Builtin(b), b)) .chain( hack::Hhbc::iter().map(|b| (FunctionName::Builtin(Builtin::Hhbc(b)), Builtin::Hhbc(b))), ) .collect(); let builtins = txf.write_epilogue(&all_builtins)?; if !no_builtins { decls::write_decls(&mut txf, &builtins)?; } txf.write_comment(&format!("{UNIT_END_MARKER} {escaped_path}"))?; txf.debug_separator()?; Ok(()) } fn check_fatal(path: &Path, fatal: Option<&ir::Fatal>) -> Result<()> { if let Some(fatal) = fatal { let err = match fatal.op { ir::FatalOp::Parse => "Parse", ir::FatalOp::Runtime => "Runtime", ir::FatalOp::RuntimeOmitFrame => "Runtime Omit", _ => unreachable!(), }; bail!( "{err} error in {}[{}]: {}", path.display(), fatal.loc.line_begin, fatal.message ); } Ok(()) }
TOML
hhvm/hphp/hack/src/hackc/ir/conversions/textual/cargo/macros/Cargo.toml
# @generated by autocargo [package] name = "textual_macros" version = "0.0.0" edition = "2021" [lib] path = "../../macros.rs" test = false doctest = false proc-macro = true [dependencies] itertools = "0.10.3" proc-macro-error = "1.0" proc-macro2 = { version = "1.0.64", features = ["span-locations"] } quote = "1.0.29" syn = { version = "1.0.109", features = ["extra-traits", "fold", "full", "visit", "visit-mut"] }
TOML
hhvm/hphp/hack/src/hackc/ir/conversions/textual/cargo/textual/Cargo.toml
# @generated by autocargo [package] name = "textual" version = "0.0.0" edition = "2021" [lib] path = "../../lib.rs" [dependencies] anyhow = "1.0.71" ascii = "1.0" escaper = { version = "0.0.0", path = "../../../../../../utils/escaper" } hash = { version = "0.0.0", path = "../../../../../../utils/hash" } ir = { version = "0.0.0", path = "../../../.." } itertools = "0.10.3" log = { version = "0.4.17", features = ["kv_unstable", "kv_unstable_std"] } naming_special_names_rust = { version = "0.0.0", path = "../../../../../../naming" } newtype = { version = "0.0.0", path = "../../../../../../utils/newtype" } strum = { version = "0.24", features = ["derive"] } textual_macros = { version = "0.0.0", path = "../macros" }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/textual/lower/class.rs
use std::sync::Arc; use ir::instr; use ir::Attr; use ir::Attribute; use ir::Class; use ir::ClassId; use ir::Coeffects; use ir::Constant; use ir::FuncBuilder; use ir::HackConstant; use ir::Instr; use ir::LocalId; use ir::MemberOpBuilder; use ir::Method; use ir::MethodFlags; use ir::MethodId; use ir::Param; use ir::PropId; use ir::Property; use ir::StringInterner; use ir::TypeInfo; use ir::Visibility; use log::trace; use crate::class::IsStatic; /// This indicates a static property that started life as a class constant. pub(crate) const INFER_CONSTANT: &str = "__Infer_Constant__"; pub(crate) fn lower_class<'a>(mut class: Class<'a>, strings: Arc<StringInterner>) -> Class<'a> { if !class.ctx_constants.is_empty() { textual_todo! { trace!("TODO: class.ctx_constants"); } } if !class.upper_bounds.is_empty() { textual_todo! { trace!("TODO: class.upper_bounds"); } } let classish_is_trait = class.is_trait(); for method in &mut class.methods { if method.name.is_86pinit(&strings) { // We want 86pinit to be 'instance' but hackc marks it as 'static'. method.attrs -= Attr::AttrStatic; } if method.flags.contains(MethodFlags::IS_CLOSURE_BODY) { // We want closure bodies to be 'instance' but hackc marks it as 'static'. method.attrs -= Attr::AttrStatic; } if classish_is_trait { // Let's insert a `self` parameter so infer's analysis can // do its job. We don't use `$` so we are sure we don't clash with // existing Hack user defined variables. let self_param = Param { name: strings.intern_str("self"), is_variadic: false, is_inout: false, is_readonly: false, user_attributes: vec![], ty: TypeInfo::empty(), default_value: None, }; method.func.params.push(self_param); } } // HHVM is okay with implicit 86pinit and 86sinit but we need to make them // explicit so we can put trivial initializers in them (done later in func // lowering). create_method_if_missing( &mut class, MethodId::_86pinit(&strings), IsStatic::NonStatic, Arc::clone(&strings), ); create_method_if_missing( &mut class, MethodId::_86sinit(&strings), IsStatic::Static, Arc::clone(&strings), ); if class.flags.contains(Attr::AttrIsClosureClass) { create_default_closure_constructor(&mut class, Arc::clone(&strings)); } // Turn class constants into properties. // TODO: Need to think about abstract constants. Maybe constants lookups // should really be function calls... for constant in class.constants.drain(..) { let HackConstant { name, value, attrs } = constant; // Mark the property as originally being a constant. let attributes = vec![Attribute { name: ClassId::from_str(INFER_CONSTANT, &strings), arguments: Vec::new(), }]; let type_info = if let Some(value) = value.as_ref() { value.type_info() } else { TypeInfo::empty() }; let prop = Property { name: PropId::new(name.id), flags: attrs | Attr::AttrStatic, attributes, visibility: Visibility::Public, initial_value: value, type_info, doc_comment: Default::default(), }; class.properties.push(prop); } class } fn create_default_closure_constructor<'a>(class: &mut Class<'a>, strings: Arc<StringInterner>) { let name = MethodId::constructor(&strings); let func = FuncBuilder::build_func(Arc::clone(&strings), |fb| { let loc = fb.add_loc(class.src_loc.clone()); fb.func.loc_id = loc; // '$this' parameter is implied. for prop in &class.properties { fb.func.params.push(Param { name: prop.name.id, is_variadic: false, is_inout: false, is_readonly: false, user_attributes: Vec::new(), ty: prop.type_info.clone(), default_value: None, }); let lid = LocalId::Named(prop.name.id); let value = fb.emit(Instr::Hhbc(instr::Hhbc::CGetL(lid, loc))); MemberOpBuilder::base_h(loc).emit_set_m_pt(fb, prop.name, value); } let null = fb.emit_constant(Constant::Null); fb.emit(Instr::ret(null, loc)); }); let method = Method { attributes: Vec::new(), attrs: Attr::AttrNone, coeffects: Coeffects::default(), flags: MethodFlags::empty(), func, name, visibility: Visibility::Public, }; class.methods.push(method); } fn create_method_if_missing<'a>( class: &mut Class<'a>, name: MethodId, is_static: IsStatic, strings: Arc<StringInterner>, ) { if class.methods.iter().any(|m| m.name == name) { return; } let func = FuncBuilder::build_func(strings, |fb| { let loc = fb.add_loc(class.src_loc.clone()); fb.func.loc_id = loc; let null = fb.emit_constant(Constant::Null); fb.emit(Instr::ret(null, loc)); }); let attrs = is_static.as_attr(); let method = Method { attributes: Vec::new(), attrs, coeffects: Coeffects::default(), flags: MethodFlags::empty(), func, name, visibility: Visibility::Private, }; class.methods.push(method); }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/textual/lower/constants.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use ir::instr; use ir::instr::HasOperands; use ir::instr::Terminator; use ir::newtype::ConstantIdSet; use ir::BlockId; use ir::BlockIdSet; use ir::Constant; use ir::ConstantId; use ir::Func; use ir::FuncBuilder; use ir::HasEdges; use ir::Instr; use ir::StringInterner; use ir::ValueId; use ir::ValueIdMap; use log::trace; /// Write the complex constants to the start of the entry block (and 'default' /// handling blocks) and remap their uses to the emitted values. pub(crate) fn write_constants(builder: &mut FuncBuilder<'_>) { // Rewrite some types of constants. for c in builder.func.constants.iter_mut() { match c { Constant::File => { // Rewrite __FILE__ as a simple string since the real filename // shouldn't matter for analysis. let id = builder.strings.intern_str("__FILE__"); *c = Constant::String(id); } _ => {} } } // Write the complex constants to the entry block. insert_constants(builder, Func::ENTRY_BID); } /// Follow the blocks successors around but stopping at an 'enter'. We stop at /// enter under the assumption that default blocks enter into the entry path - /// so those will be handled separately. fn follow_block_successors(func: &Func<'_>, bid: BlockId) -> Vec<BlockId> { let mut result = Vec::new(); let mut processed = BlockIdSet::default(); let mut pending = vec![bid]; while let Some(bid) = pending.pop() { processed.insert(bid); result.push(bid); // Add unprocessed successors to pending. let terminator = func.terminator(bid); match terminator { Terminator::Enter(..) => { // We don't want to trace through Enter. } terminator => { for edge in terminator.edges() { if !processed.contains(edge) { pending.push(*edge); } } } } // And catch handlers let handler = func.catch_target(bid); if handler != BlockId::NONE && !processed.contains(&handler) { pending.push(handler); } } result } /// Compute the set of constants that are visible starting from `bid`. fn compute_live_constants(func: &Func<'_>, bids: &Vec<BlockId>) -> ConstantIdSet { let mut visible = ConstantIdSet::default(); for &bid in bids { let block = func.block(bid); visible.extend( block .iids() .map(|iid| func.instr(iid)) .flat_map(|instr| instr.operands().iter().filter_map(|op| op.constant())), ); } visible } fn remap_constants(func: &mut Func<'_>, bids: &Vec<BlockId>, remap: ValueIdMap<ValueId>) { for &bid in bids { func.remap_block_vids(bid, &remap); } } fn insert_constants(builder: &mut FuncBuilder<'_>, start_bid: BlockId) { // Allocate a new block, fill it with constants, append the old InstrIds, // swap the old and new blocks and then clear the new block. let bids = follow_block_successors(&builder.func, start_bid); let constants = compute_live_constants(&builder.func, &bids); let constants = sort_and_filter_constants(&builder.func, constants, &builder.strings); let mut remap = ValueIdMap::default(); let mut fixups = Vec::default(); let new_bid = builder.alloc_bid(); builder.start_block(new_bid); for cid in constants.into_iter() { let (vid, needs_fixup) = write_constant(builder, cid); let src = ValueId::from_constant(cid); remap.insert(src, vid); if needs_fixup { fixups.push((vid, src)); } } let mut old_iids = std::mem::take(&mut builder.func.block_mut(start_bid).iids); builder.cur_block_mut().iids.append(&mut old_iids); builder.func.blocks.swap(start_bid, new_bid); remap_constants(&mut builder.func, &bids, remap); for (vid, src) in fixups { let iid = vid.instr().unwrap(); builder.func.instrs[iid] = Instr::Special(instr::Special::Copy(src)); } } /// Arrays can refer to some prior constants (like Strings) so they need to be /// sorted before being written. Right now arrays can't refer to other arrays so /// they don't need to be sorted relative to each other. fn sort_and_filter_constants( func: &Func<'_>, constants: ConstantIdSet, string_intern: &StringInterner, ) -> Vec<ConstantId> { let mut result = Vec::with_capacity(constants.len()); let mut arrays = Vec::with_capacity(constants.len()); for cid in constants { let constant = func.constant(cid); match constant { Constant::Bool(..) | Constant::Dir | Constant::Float(..) | Constant::File | Constant::FuncCred | Constant::Int(..) | Constant::Method | Constant::NewCol(..) | Constant::Null | Constant::Uninit => {} Constant::Array(_) => { arrays.push(cid); } Constant::Named(..) => { result.push(cid); } Constant::String(s) => { // If the string is short then just keep it inline. This makes // it easier to visually read the output but may be more work // for infer (because it's a call)... if string_intern.lookup_bstr(*s).len() > 40 { result.push(cid); } } } } result.append(&mut arrays); result } fn write_constant(builder: &mut FuncBuilder<'_>, cid: ConstantId) -> (ValueId, bool) { let constant = builder.func.constant(cid); trace!(" Const {cid}: {constant:?}"); match constant { Constant::Bool(..) | Constant::Dir | Constant::Float(..) | Constant::File | Constant::FuncCred | Constant::Int(..) | Constant::Method | Constant::NewCol(..) | Constant::Null | Constant::Uninit => unreachable!(), // Insert a tombstone which will be turned into a 'copy' later. Constant::Array(_) | Constant::String(_) => (builder.emit(Instr::tombstone()), true), Constant::Named(name) => { let id = ir::GlobalId::new(ir::ConstId::from_hhbc(*name, &builder.strings).id); let vid = builder.emit(Instr::Special(ir::instr::Special::Textual( ir::instr::Textual::LoadGlobal { id, is_const: true }, ))); (vid, false) } } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/textual/lower/func.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::sync::Arc; use ir::instr::Hhbc; use ir::Constant; use ir::Func; use ir::FuncBuilder; use ir::Instr; use ir::LocId; use ir::LocalId; use ir::MemberOpBuilder; use ir::MethodFlags; use ir::MethodId; use ir::ReadonlyOp; use ir::SpecialClsRef; use ir::StringInterner; use ir::TypedValue; use log::trace; use crate::func::FuncInfo; use crate::func::MethodInfo; pub(crate) fn lower_func<'a>( mut func: Func<'a>, func_info: &mut FuncInfo<'_>, strings: Arc<StringInterner>, ) -> Func<'a> { trace!( "{} Before Lower: {}", func_info.name_id().display(&strings), ir::print::DisplayFunc::new(&func, true, &strings) ); // In a closure we implicitly load all the properties as locals - so start // with that as a prelude to all entrypoints. match *func_info { FuncInfo::Method(ref mut method_info) => { if method_info.flags.contains(MethodFlags::IS_CLOSURE_BODY) { load_closure_vars(&mut func, method_info, &strings); } } FuncInfo::Function(_) => {} } // Start by 'unasync'ing the Func. ir::passes::unasync(&mut func); trace!( "After unasync: {}", ir::print::DisplayFunc::new(&func, true, &strings) ); let mut builder = FuncBuilder::with_func(func, Arc::clone(&strings)); match func_info { FuncInfo::Method(mi) if mi.name.is_86pinit(&strings) => { rewrite_86pinit(&mut builder, mi); } FuncInfo::Method(mi) if mi.name.is_86sinit(&strings) => { rewrite_86sinit(&mut builder, mi); } _ => {} } // Simplify various Instrs. super::instrs::lower_instrs(&mut builder, func_info); trace!( "After lower_instrs: {}", ir::print::DisplayFunc::new(&builder.func, true, &strings) ); // Write the complex constants out as a prelude to the function. super::constants::write_constants(&mut builder); let mut func = builder.finish(); ir::passes::split_critical_edges(&mut func, true); ir::passes::clean::run(&mut func); trace!( "After Lower: {}", ir::print::DisplayFunc::new(&func, true, &strings) ); func } fn call_base_func(builder: &mut FuncBuilder<'_>, method_info: &MethodInfo<'_>, loc: LocId) { if method_info.class.base.is_some() { let clsref = SpecialClsRef::ParentCls; let method = method_info.name; builder.emit(Instr::method_call_special(clsref, method, &[], loc)); } } fn rewrite_86pinit(builder: &mut FuncBuilder<'_>, method_info: &MethodInfo<'_>) { // In HHVM 86pinit is only used to initialize "complex" properties (and // doesn't exist if there aren't any). For textual we change that to use it // to initialize all properties and be guaranteed to exist. builder.start_block(Func::ENTRY_BID); let saved = std::mem::take(&mut builder.cur_block_mut().iids); let loc = builder.func.loc_id; call_base_func(builder, method_info, loc); // Init the properties. for prop in &method_info.class.properties { match prop { ir::Property { name, flags, initial_value: Some(initial_value), .. } if !flags.is_static() => { let vid = builder.emit_constant(initial_value.clone().into()); MemberOpBuilder::base_h(loc).emit_set_m_pt(builder, *name, vid); } _ => {} } } builder.cur_block_mut().iids.extend(saved); } fn rewrite_86sinit(builder: &mut FuncBuilder<'_>, method_info: &MethodInfo<'_>) { // In HHVM 86sinit is only used to initialize "complex" static properties // (and doesn't exist if there aren't any). For textual we change that to // use it to initialize all properties and be guaranteed to exist. We also // use it to initialize class constants. builder.start_block(Func::ENTRY_BID); let saved = std::mem::take(&mut builder.cur_block_mut().iids); let loc = builder.func.loc_id; call_base_func(builder, method_info, loc); let class = &method_info.class; let infer_const = ir::ClassId::from_str(crate::lower::class::INFER_CONSTANT, &builder.strings); // Now emit the static properties. let cls_name = builder.emit_constant(Constant::String(class.name.id)); let cls = builder.emit(Instr::Hhbc(Hhbc::ClassGetC(cls_name, loc))); for prop in &class.properties { if !prop.flags.is_static() { continue; } let is_const = prop.attributes.iter().any(|attr| attr.name == infer_const); let vid = match prop { ir::Property { name, initial_value: Some(TypedValue::Uninit), .. } if is_const => { // This is a "complex" constant - we need to call 86cinit to get // the value. let clsref = SpecialClsRef::SelfCls; let method = MethodId::_86cinit(&builder.strings); let name = builder.emit_constant(Constant::String(name.id)); Some(builder.emit(Instr::method_call_special(clsref, method, &[name], loc))) } ir::Property { initial_value: None, .. } if is_const => { // This is an abstract constant - its value will be overwritten // in a subclass's init - so just skip it. continue; } ir::Property { initial_value: Some(initial_value), .. } => { // Either a normal property or non-complex constant. Some(builder.emit_constant(initial_value.clone().into())) } _ => None, }; if let Some(vid) = vid { let prop_name = builder.emit_constant(Constant::String(prop.name.id)); builder.emit(Instr::Hhbc(Hhbc::SetS( [prop_name, cls, vid], ReadonlyOp::Any, loc, ))); } } builder.cur_block_mut().iids.extend(saved); } fn load_closure_vars(func: &mut Func<'_>, method_info: &MethodInfo<'_>, strings: &StringInterner) { let mut instrs = Vec::new(); let loc = func.loc_id; for prop in &method_info.class.properties { // Property names are the variable names without the '$'. let prop_str = strings.lookup_bstr(prop.name.id); let mut var = prop_str.to_vec(); var.insert(0, b'$'); let lid = LocalId::Named(strings.intern_bytes(var)); let iid = func.alloc_instr(Instr::MemberOp( MemberOpBuilder::base_h(loc).query_pt(prop.name), )); instrs.push(iid); instrs.push(func.alloc_instr(Instr::Hhbc(Hhbc::SetL(iid.into(), lid, loc)))); } func.block_mut(Func::ENTRY_BID).iids.splice(0..0, instrs); }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/textual/lower/func_builder.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. //! Helpers for FuncBuilder emitting Textual specific constructs during lowering. use std::borrow::Cow; use ir::FuncBuilder; use ir::Instr; use ir::LocId; use ir::ValueId; use crate::hack; pub(crate) trait FuncBuilderEx { /// Build a hack::Builtin call. fn hack_builtin(&mut self, builtin: hack::Builtin, args: &[ValueId], loc: LocId) -> Instr; fn emit_hack_builtin( &mut self, builtin: hack::Builtin, args: &[ValueId], loc: LocId, ) -> ValueId; fn hhbc_builtin(&mut self, builtin: hack::Hhbc, args: &[ValueId], loc: LocId) -> Instr { self.hack_builtin(hack::Builtin::Hhbc(builtin), args, loc) } fn emit_hhbc_builtin(&mut self, builtin: hack::Hhbc, args: &[ValueId], loc: LocId) -> ValueId { self.emit_hack_builtin(hack::Builtin::Hhbc(builtin), args, loc) } } impl<'a> FuncBuilderEx for FuncBuilder<'a> { fn hack_builtin(&mut self, builtin: hack::Builtin, args: &[ValueId], loc: LocId) -> Instr { let target = Cow::Borrowed(builtin.as_str()); let values = args.to_vec().into_boxed_slice(); Instr::Special(ir::instr::Special::Textual( ir::instr::Textual::HackBuiltin { target, values, loc, }, )) } fn emit_hack_builtin( &mut self, builtin: hack::Builtin, args: &[ValueId], loc: LocId, ) -> ValueId { let instr = self.hack_builtin(builtin, args, loc); self.emit(instr) } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/textual/lower/instrs.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use ir::func_builder::TransformInstr; use ir::func_builder::TransformState; use ir::instr::CallDetail; use ir::instr::CmpOp; use ir::instr::HasLoc; use ir::instr::HasLocals; use ir::instr::HasOperands; use ir::instr::Hhbc; use ir::instr::IteratorArgs; use ir::instr::MemberOp; use ir::instr::MemoGet; use ir::instr::MemoGetEager; use ir::instr::Predicate; use ir::instr::Special; use ir::instr::Terminator; use ir::instr::Textual; use ir::type_struct::TypeStruct; use ir::BareThisOp; use ir::Call; use ir::Constant; use ir::FCallArgsFlags; use ir::Func; use ir::FuncBuilder; use ir::FuncBuilderEx as _; use ir::GlobalId; use ir::InitPropOp; use ir::Instr; use ir::InstrId; use ir::IsTypeOp; use ir::LocId; use ir::LocalId; use ir::MemberOpBuilder; use ir::MethodId; use ir::ObjMethodOp; use ir::PropId; use ir::ReadonlyOp; use ir::SpecialClsRef; use ir::TypeStructResolveOp; use ir::UnitBytesId; use ir::ValueId; use itertools::Itertools; use super::func_builder::FuncBuilderEx as _; use crate::class::IsStatic; use crate::func::lookup_constant; use crate::func::lookup_constant_string; use crate::func::FuncInfo; use crate::hack; /// Lower individual Instrs in the Func to simpler forms. pub(crate) fn lower_instrs(builder: &mut FuncBuilder<'_>, func_info: &FuncInfo<'_>) { let mut lowerer = LowerInstrs { changed: false, func_info, }; let mut bid = Func::ENTRY_BID; while bid.0 < builder.func.blocks.len() as u32 { lowerer.changed = true; while lowerer.changed { // The lowered instructions may have emitted stuff that needs to be // lowered again. This could be optimized by only setting `changed` // when we think we need to loop. lowerer.changed = false; builder.rewrite_block(bid, &mut lowerer); } bid.0 += 1; } } struct LowerInstrs<'a> { changed: bool, func_info: &'a FuncInfo<'a>, } impl LowerInstrs<'_> { fn c_get_g(&self, builder: &mut FuncBuilder<'_>, vid: ValueId, _loc: LocId) -> Option<Instr> { // A lot of times the name for the global comes from a static // string name - see if we can dig it up and turn this into a // Textual::LoadGlobal. vid.constant() .and_then(|cid| match builder.func.constant(cid) { Constant::String(s) => { let id = ir::GlobalId::new(*s); Some(Instr::Special(Special::Textual(Textual::LoadGlobal { id, is_const: false, }))) } _ => None, }) } fn handle_hhbc_with_builtin(&self, hhbc: &Hhbc) -> Option<hack::Hhbc> { let builtin = match hhbc { Hhbc::Add(..) => hack::Hhbc::Add, Hhbc::AddElemC(..) => hack::Hhbc::AddElemC, Hhbc::AddNewElemC(..) => hack::Hhbc::AddNewElemC, Hhbc::Await(..) => hack::Hhbc::Await, Hhbc::AwaitAll(..) => hack::Hhbc::AwaitAll, Hhbc::CastKeyset(..) => hack::Hhbc::CastKeyset, Hhbc::CastString(..) => hack::Hhbc::CastString, Hhbc::CastVec(..) => hack::Hhbc::CastVec, Hhbc::ClassGetC(..) => hack::Hhbc::ClassGetC, Hhbc::CheckClsRGSoft(..) => hack::Hhbc::CheckClsRGSoft, Hhbc::CmpOp(_, CmpOp::Eq, _) => hack::Hhbc::CmpEq, Hhbc::CmpOp(_, CmpOp::Gt, _) => hack::Hhbc::CmpGt, Hhbc::CmpOp(_, CmpOp::Gte, _) => hack::Hhbc::CmpGte, Hhbc::CmpOp(_, CmpOp::Lt, _) => hack::Hhbc::CmpLt, Hhbc::CmpOp(_, CmpOp::Lte, _) => hack::Hhbc::CmpLte, Hhbc::CmpOp(_, CmpOp::NSame, _) => hack::Hhbc::CmpNSame, Hhbc::CmpOp(_, CmpOp::Neq, _) => hack::Hhbc::CmpNeq, Hhbc::CmpOp(_, CmpOp::Same, _) => hack::Hhbc::CmpSame, Hhbc::CombineAndResolveTypeStruct(..) => hack::Hhbc::CombineAndResolveTypeStruct, Hhbc::Concat(..) => hack::Hhbc::Concat, Hhbc::ConcatN(..) => hack::Hhbc::ConcatN, Hhbc::Div(..) => hack::Hhbc::Div, Hhbc::GetClsRGProp(..) => hack::Hhbc::GetClsRGProp, Hhbc::GetMemoKeyL(..) => hack::Hhbc::GetMemoKeyL, Hhbc::Idx(..) => hack::Hhbc::Idx, Hhbc::IsLateBoundCls(..) => hack::Hhbc::IsLateBoundCls, Hhbc::IsTypeC(_, IsTypeOp::ArrLike, _) => hack::Hhbc::IsTypeArrLike, Hhbc::IsTypeC(_, IsTypeOp::Bool, _) => hack::Hhbc::IsTypeBool, Hhbc::IsTypeC(_, IsTypeOp::Class, _) => hack::Hhbc::IsTypeClass, Hhbc::IsTypeC(_, IsTypeOp::ClsMeth, _) => hack::Hhbc::IsTypeClsMeth, Hhbc::IsTypeC(_, IsTypeOp::Dbl, _) => hack::Hhbc::IsTypeDbl, Hhbc::IsTypeC(_, IsTypeOp::Dict, _) => hack::Hhbc::IsTypeDict, Hhbc::IsTypeC(_, IsTypeOp::Func, _) => hack::Hhbc::IsTypeFunc, Hhbc::IsTypeC(_, IsTypeOp::Int, _) => hack::Hhbc::IsTypeInt, Hhbc::IsTypeC(_, IsTypeOp::Keyset, _) => hack::Hhbc::IsTypeKeyset, Hhbc::IsTypeC(_, IsTypeOp::LegacyArrLike, _) => hack::Hhbc::IsTypeLegacyArrLike, Hhbc::IsTypeC(_, IsTypeOp::Null, _) => hack::Hhbc::IsTypeNull, Hhbc::IsTypeC(_, IsTypeOp::Obj, _) => hack::Hhbc::IsTypeObj, Hhbc::IsTypeC(_, IsTypeOp::Res, _) => hack::Hhbc::IsTypeRes, Hhbc::IsTypeC(_, IsTypeOp::Scalar, _) => hack::Hhbc::IsTypeScalar, Hhbc::IsTypeC(_, IsTypeOp::Str, _) => hack::Hhbc::IsTypeStr, Hhbc::IsTypeC(_, IsTypeOp::Vec, _) => hack::Hhbc::IsTypeVec, Hhbc::LazyClassFromClass(..) => hack::Hhbc::LazyClassFromClass, Hhbc::Modulo(..) => hack::Hhbc::Modulo, Hhbc::Mul(..) => hack::Hhbc::Mul, Hhbc::NewDictArray(..) => hack::Hhbc::NewDictArray, Hhbc::NewKeysetArray(..) => hack::Hhbc::NewKeysetArray, Hhbc::NewVec(..) => hack::Hhbc::NewVec, Hhbc::Not(..) => hack::Hhbc::Not, Hhbc::Print(..) => hack::Hhbc::Print, Hhbc::RecordReifiedGeneric(..) => hack::Hhbc::RecordReifiedGeneric, Hhbc::Sub(..) => hack::Hhbc::Sub, Hhbc::ThrowNonExhaustiveSwitch(..) => hack::Hhbc::ThrowNonExhaustiveSwitch, Hhbc::WHResult(..) => hack::Hhbc::WHResult, _ => return None, }; Some(builtin) } fn handle_terminator_with_builtin(&self, term: &Terminator) -> Option<hack::Hhbc> { let builtin = match term { Terminator::Exit(..) => hack::Hhbc::Exit, Terminator::Throw(..) => hack::Hhbc::Throw, Terminator::ThrowAsTypeStructException(..) => hack::Hhbc::ThrowAsTypeStructException, _ => return None, }; Some(builtin) } fn handle_with_builtin(&self, builder: &mut FuncBuilder<'_>, instr: &Instr) -> Option<Instr> { let loc = instr.loc_id(); match instr { Instr::Hhbc(hhbc) => { let hhbc = self.handle_hhbc_with_builtin(hhbc)?; Some( match (instr.locals().is_empty(), instr.operands().is_empty()) { (true, true) => builder.hhbc_builtin(hhbc, &[], loc), (true, false) => builder.hhbc_builtin(hhbc, instr.operands(), loc), (false, true) => { let ops = Self::get_locals(builder, instr.locals(), loc); builder.hhbc_builtin(hhbc, &ops, loc) } (false, false) => panic!( "Unable to handle mixed instruction (locals and operands) as a built-in: {hhbc:?}" ), }, ) } Instr::MemberOp(member_op) => self.handle_member_op(builder, member_op), Instr::Terminator(term) => { let hhbc = self.handle_terminator_with_builtin(term)?; builder.emit_hhbc_builtin(hhbc, instr.operands(), loc); Some(Instr::unreachable()) } _ => None, } } fn handle_member_op( &self, builder: &mut FuncBuilder<'_>, member_op: &MemberOp, ) -> Option<Instr> { use ir::instr::BaseOp; match member_op.base_op { BaseOp::BaseSC { mode, readonly, loc, } => { let mut operands = member_op.operands.iter().copied(); let locals = member_op.locals.iter().copied(); let intermediates = member_op.intermediate_ops.iter().cloned(); let prop = operands.next().unwrap(); let base = operands.next().unwrap(); if let Some(propname) = lookup_constant_string(&builder.func, prop) { // Convert BaseSC w/ constant string to BaseST let pid = PropId::new(propname); let mut mop = MemberOpBuilder::base_st(base, pid, mode, readonly, loc); mop.operands.extend(operands); mop.locals.extend(locals); mop.intermediate_ops.extend(intermediates); return Some(Instr::MemberOp(mop.final_op(member_op.final_op.clone()))); } } _ => {} } None } fn check_prop(&self, builder: &mut FuncBuilder<'_>, _pid: PropId, _loc: LocId) -> Instr { // CheckProp checks to see if the prop has already been initialized - we'll just always say "no". Instr::copy(builder.emit_constant(Constant::Bool(false))) } fn init_prop( &self, builder: &mut FuncBuilder<'_>, vid: ValueId, pid: PropId, _op: InitPropOp, loc: LocId, ) -> Instr { // $this->pid = vid MemberOpBuilder::base_h(loc).emit_set_m_pt(builder, pid, vid); Instr::tombstone() } fn iter_init( &self, builder: &mut FuncBuilder<'_>, args: IteratorArgs, container: ValueId, ) -> Instr { // iterator ^0 init from %0 jmp to b2 else b1 with $index // -> // %n = hack::iter_init(&iter0, /* key */ null, &$index, %0) // if %n jmp b1 else b2 let loc = args.loc; let iter_lid = iter_var_name(args.iter_id, &builder.strings); let iter_var = builder.emit(Textual::deref(iter_lid)); let value_var = builder.emit(Textual::deref(args.value_lid())); let key_var = if let Some(key_lid) = args.key_lid() { builder.emit(Textual::deref(key_lid)) } else { builder.emit_constant(Constant::Null) }; let pred = builder.emit_hhbc_builtin( hack::Hhbc::IterInit, &[iter_var, key_var, value_var, container], loc, ); Instr::jmp_op( pred, Predicate::NonZero, args.next_bid(), args.done_bid(), loc, ) } fn iter_next(&self, builder: &mut FuncBuilder<'_>, args: IteratorArgs) -> Instr { // iterator ^0 next jmp to b2 else b1 with $index // -> // %n = hack::iter_next(&iter0, /* key */ null, &$index) // if %n jmp b1 else b2 let loc = args.loc; let iter_lid = iter_var_name(args.iter_id, &builder.strings); let value_var = builder.emit(Textual::deref(args.value_lid())); let key_var = if let Some(key_lid) = args.key_lid() { builder.emit(Textual::deref(key_lid)) } else { builder.emit_constant(Constant::Null) }; let iter_var = builder.emit(Instr::Hhbc(Hhbc::CGetL(iter_lid, loc))); let pred = builder.emit_hhbc_builtin(hack::Hhbc::IterNext, &[iter_var, key_var, value_var], loc); Instr::jmp_op( pred, Predicate::NonZero, args.next_bid(), args.done_bid(), loc, ) } fn get_locals<'s>( builder: &mut FuncBuilder<'s>, locals: &[LocalId], loc: LocId, ) -> Vec<ValueId> { locals .iter() .map(|lid| builder.emit(Instr::Hhbc(Hhbc::CGetL(*lid, loc)))) .collect() } fn compute_memo_ops( &self, builder: &mut FuncBuilder<'_>, locals: &[LocalId], loc: LocId, ) -> Vec<ValueId> { let name = match *self.func_info { FuncInfo::Method(ref mi) => { crate::mangle::FunctionName::method(mi.class.name, mi.is_static, mi.name) } FuncInfo::Function(ref fi) => crate::mangle::FunctionName::Function(fi.name), }; let mut ops = Vec::new(); let name = format!("{}", name.display(&builder.strings)); let name = GlobalId::new(builder.strings.intern_str(format!( "memocache::{}", crate::util::escaped_ident(name.into()) ))); // NOTE: This is called 'LocalId' but actually represents a GlobalId // (because we don't have a DerefGlobal instr - but it would work the // same with just a different type). let global = builder.emit(Textual::deref(LocalId::Named(name.id))); ops.push(global); match *self.func_info { FuncInfo::Method(_) => { let this = builder.strings.intern_str("$this"); let lid = LocalId::Named(this); ops.push(builder.emit(Instr::Hhbc(Hhbc::CGetL(lid, loc)))); } FuncInfo::Function(_) => {} }; ops.extend(Self::get_locals(builder, locals, loc).into_iter()); ops } fn memo_get(&self, builder: &mut FuncBuilder<'_>, memo_get: MemoGet) -> Instr { // memo_get([$a, $b], b1, b2) // -> // global NAME // if memo_isset($this, $a, $b) { // tmp = memo_get($this, $a, $b) // goto b1(tmp); // } else { // goto b2; // } let loc = memo_get.loc; let ops = self.compute_memo_ops(builder, &memo_get.locals, loc); let pred = builder.emit_hack_builtin(hack::Builtin::MemoIsset, &ops, loc); builder.emit_if_then_else( pred, loc, |builder| { let value = builder.emit_hack_builtin(hack::Builtin::MemoGet, &ops, loc); Instr::jmp_args(memo_get.edges[0], &[value], loc) }, |_| Instr::jmp(memo_get.edges[1], loc), ); Instr::tombstone() } fn memo_get_eager(&self, builder: &mut FuncBuilder<'_>, mge: MemoGetEager) -> Instr { // MemoGetEager is the async version of MemoGet. Ignore the async edge // and just treat it as a MemoGet. self.memo_get( builder, MemoGet::new(mge.eager_edge(), mge.no_value_edge(), &mge.locals, mge.loc), ) } fn memo_set( &self, builder: &mut FuncBuilder<'_>, vid: ValueId, locals: &[LocalId], loc: LocId, ) -> Instr { let mut ops = self.compute_memo_ops(builder, locals, loc); ops.push(vid); builder.hhbc_builtin(hack::Hhbc::MemoSet, &ops, loc) } fn memo_set_eager( &self, builder: &mut FuncBuilder<'_>, vid: ValueId, locals: &[LocalId], loc: LocId, ) -> Instr { // MemoSetEager is the async version of MemoSet. Ignore the async edge // and just treat it as a MemoSet. self.memo_set(builder, vid, locals, loc) } fn verify_out_type( &self, builder: &mut FuncBuilder<'_>, obj: ValueId, lid: LocalId, loc: LocId, ) -> Instr { let param = builder .func .get_param_by_lid(lid) .expect("Unknown parameter in verify_out_type()"); let param_type = param.ty.enforced.clone(); let pred = builder.emit_is(obj, &param_type, loc); builder.emit_hack_builtin(hack::Builtin::VerifyTypePred, &[obj, pred], loc); Instr::copy(obj) } fn verify_param_type_ts( &self, builder: &mut FuncBuilder<'_>, lid: LocalId, ts: ValueId, loc: LocId, ) -> Instr { let obj = builder.emit(Instr::Hhbc(Hhbc::CGetL(lid, loc))); let builtin = hack::Hhbc::VerifyParamTypeTS; builder.emit_hhbc_builtin(builtin, &[obj, ts], loc); Instr::tombstone() } fn verify_ret_type_c(&self, builder: &mut FuncBuilder<'_>, obj: ValueId, loc: LocId) -> Instr { let return_type = builder.func.return_type.enforced.clone(); let pred = builder.emit_is(obj, &return_type, loc); builder.emit_hack_builtin(hack::Builtin::VerifyTypePred, &[obj, pred], loc); Instr::copy(obj) } fn verify_ret_type_ts( &self, builder: &mut FuncBuilder<'_>, obj: ValueId, ts: ValueId, loc: LocId, ) -> Instr { let builtin = hack::Hhbc::VerifyParamTypeTS; builder.emit_hhbc_builtin(builtin, &[obj, ts], loc); Instr::copy(obj) } fn emit_special_cls_ref( &mut self, builder: &mut FuncBuilder<'_>, clsref: SpecialClsRef, loc: LocId, ) -> ValueId { match clsref { SpecialClsRef::SelfCls => builder.emit(Instr::Hhbc(Hhbc::SelfCls(loc))), SpecialClsRef::LateBoundCls => builder.emit(Instr::Hhbc(Hhbc::LateBoundCls(loc))), SpecialClsRef::ParentCls => builder.emit(Instr::Hhbc(Hhbc::ParentCls(loc))), _ => unreachable!(), } } fn set_s( &mut self, builder: &mut FuncBuilder<'_>, field: ValueId, class: ValueId, vid: ValueId, _readonly: ReadonlyOp, loc: LocId, ) -> Option<Instr> { // Some magic - if the class points to a ClassGetC with a // constant parameter and the field is a constant then replace // this with a Textual::SetPropD. if let Some(propname) = lookup_constant_string(&builder.func, field) { if let Some(class) = class.instr() { let class_instr = builder.func.instr(class); // The ClassGetC will have already been converted to a // textual builtin. if let Instr::Special(Special::Textual(Textual::HackBuiltin { target, values: box [cid], loc: _, })) = class_instr { if target == hack::Hhbc::ClassGetC.as_str() { if let Some(classname) = lookup_constant_string(&builder.func, *cid) { let cid = builder.emit_constant(Constant::String(classname)); let pid = builder.emit_constant(Constant::String(propname)); return Some(builder.hack_builtin( hack::Builtin::SetStaticProp, &[cid, pid, vid], loc, )); } } } } } None } } impl TransformInstr for LowerInstrs<'_> { fn apply( &mut self, iid: InstrId, instr: Instr, builder: &mut FuncBuilder<'_>, state: &mut TransformState, ) -> Instr { use hack::Builtin; if let Some(instr) = self.handle_with_builtin(builder, &instr) { self.changed = true; return instr; } let instr = match instr { // NOTE: Be careful trying to lower most Instr::Call - the details // matter and it's hard to rewrite them to preserve those details // properly. Instr::Call( box mut call @ Call { detail: CallDetail::FCallCtor, .. }, ) => { let flavor = ObjMethodOp::NullThrows; let method = MethodId::constructor(&builder.strings); call.detail = CallDetail::FCallObjMethodD { flavor, method }; Instr::Call(Box::new(call)) } Instr::Call( box call @ Call { detail: CallDetail::FCallObjMethod { flavor: ObjMethodOp::NullSafe, .. } | CallDetail::FCallObjMethodD { flavor: ObjMethodOp::NullSafe, .. }, .. }, ) => rewrite_nullsafe_call(iid, builder, call, state), Instr::Hhbc(Hhbc::BareThis(_op, loc)) => { let this = builder.strings.intern_str("$this"); let lid = LocalId::Named(this); Instr::Hhbc(Hhbc::CGetL(lid, loc)) } Instr::Hhbc(Hhbc::SetS([field, class, vid], readonly, loc)) => { if let Some(replace) = self.set_s(builder, field, class, vid, readonly, loc) { replace } else { return instr; } } Instr::Hhbc(Hhbc::CheckProp(pid, loc)) => self.check_prop(builder, pid, loc), Instr::Hhbc(Hhbc::CheckThis(loc)) => { let builtin = hack::Hhbc::CheckThis; let op = BareThisOp::NoNotice; let this = builder.emit(Instr::Hhbc(Hhbc::BareThis(op, loc))); builder.hhbc_builtin(builtin, &[this], loc) } Instr::Hhbc(Hhbc::CGetG(name, loc)) => { if let Some(instr) = self.c_get_g(builder, name, loc) { instr } else { return Instr::Hhbc(Hhbc::CGetG(name, loc)); } } Instr::Hhbc(Hhbc::ClsCns(cls, const_id, loc)) => { let builtin = hack::Hhbc::ClsCns; let const_id = builder.emit_constant(Constant::String(const_id.id)); builder.hhbc_builtin(builtin, &[cls, const_id], loc) } Instr::Hhbc(Hhbc::ClsCnsD(const_id, cid, loc)) => { // ClsCnsD(id, cid) -> CGetS(id, cid) let cid = builder.emit_constant(Constant::String(cid.id)); let const_id = builder.emit_constant(Constant::String(const_id.id)); Instr::Hhbc(Hhbc::CGetS([const_id, cid], ReadonlyOp::Readonly, loc)) } Instr::Hhbc(Hhbc::ColFromArray(vid, col_type, loc)) => { use ir::CollectionType; let builtin = match col_type { CollectionType::ImmMap => hack::Hhbc::ColFromArrayImmMap, CollectionType::ImmSet => hack::Hhbc::ColFromArrayImmSet, CollectionType::ImmVector => hack::Hhbc::ColFromArrayImmVector, CollectionType::Map => hack::Hhbc::ColFromArrayMap, CollectionType::Pair => hack::Hhbc::ColFromArrayPair, CollectionType::Set => hack::Hhbc::ColFromArraySet, CollectionType::Vector => hack::Hhbc::ColFromArrayVector, other => panic!("Unknown collection type: {:?}", other), }; builder.hhbc_builtin(builtin, &[vid], loc) } Instr::Hhbc(Hhbc::InitProp(vid, pid, op, loc)) => { self.init_prop(builder, vid, pid, op, loc) } Instr::Hhbc(Hhbc::IsTypeStructC([obj, ts], op, loc)) => { let builtin = hack::Hhbc::IsTypeStructC; let op = match op { TypeStructResolveOp::DontResolve => 0, TypeStructResolveOp::Resolve => 1, _ => unreachable!(), }; match rewrite_constant_type_check(builder, obj, ts, loc) { Some(null_check) => null_check, None => { let op = builder.emit_constant(Constant::Int(op)); builder.hhbc_builtin(builtin, &[obj, ts, op], loc) } } } Instr::Hhbc(Hhbc::LateBoundCls(loc)) => match *self.func_info { FuncInfo::Method(ref mi) => match mi.is_static { IsStatic::Static => { let this = builder.emit(Instr::Hhbc(Hhbc::This(loc))); builder.hack_builtin(Builtin::GetClass, &[this], loc) } IsStatic::NonStatic => { let this = builder.emit(Instr::Hhbc(Hhbc::This(loc))); builder.hack_builtin(Builtin::GetStaticClass, &[this], loc) } }, FuncInfo::Function(_) => unreachable!(), }, Instr::Hhbc(Hhbc::LazyClass(clsid, _)) => { // Treat a lazy class as a simple string. let c = builder.emit_constant(Constant::String(clsid.id)); Instr::copy(c) } Instr::Hhbc(Hhbc::LockObj(obj, loc)) => { builder.emit_hhbc_builtin(hack::Hhbc::LockObj, &[obj], loc); Instr::copy(obj) } Instr::Hhbc(Hhbc::MemoSet(vid, locals, loc)) => { self.memo_set(builder, vid, &locals, loc) } Instr::Hhbc(Hhbc::MemoSetEager(vid, locals, loc)) => { self.memo_set_eager(builder, vid, &locals, loc) } Instr::Hhbc(Hhbc::NewStructDict(names, values, loc)) => { let args = names .iter() .zip(values.iter().copied()) .flat_map(|(name, value)| { [builder.emit_constant(Constant::String(*name)), value] }) .collect_vec(); builder.hack_builtin(Builtin::NewDict, &args, loc) } Instr::Hhbc(Hhbc::NewObj(cls, loc)) => { let method = MethodId::factory(&builder.strings); let operands = vec![cls].into_boxed_slice(); let context = UnitBytesId::NONE; let flavor = ObjMethodOp::NullThrows; let detail = CallDetail::FCallObjMethodD { flavor, method }; let flags = FCallArgsFlags::default(); Instr::Call(Box::new(Call { operands, context, detail, flags, num_rets: 1, inouts: None, readonly: None, loc, })) } Instr::Hhbc(Hhbc::NewObjS(clsref, loc)) => { let cls = self.emit_special_cls_ref(builder, clsref, loc); Instr::Hhbc(Hhbc::NewObj(cls, loc)) } Instr::Hhbc(Hhbc::SelfCls(loc)) if self.func_info.declared_in_trait() => { // In a trait, turn the `self` keyword into the fresh parameter we add // to the type signatures. let lid = builder.strings.intern_str("self"); let lid = LocalId::Named(lid); Instr::Hhbc(Hhbc::CGetL(lid, loc)) } Instr::Hhbc(Hhbc::Silence(..)) => { // Silence sets hhvm error reporting level, no-op here Instr::tombstone() } Instr::Hhbc(Hhbc::VerifyOutType(vid, lid, loc)) => { self.verify_out_type(builder, vid, lid, loc) } Instr::Hhbc(Hhbc::VerifyParamType(vid, _lid, _loc)) => { // This is used to check the param type of default // parameters. We'll hold off on actually checking for now since // it's hard to turn the param type into a checkable TypeStruct // (and right now the param type has been erased in this version // of the function). Instr::Special(Special::Copy(vid)) } Instr::Hhbc(Hhbc::VerifyParamTypeTS(ts, lid, loc)) => { self.verify_param_type_ts(builder, lid, ts, loc) } Instr::Hhbc(Hhbc::VerifyRetTypeC(vid, loc)) => { self.verify_ret_type_c(builder, vid, loc) } Instr::Hhbc(Hhbc::VerifyRetTypeTS([obj, ts], loc)) => { self.verify_ret_type_ts(builder, obj, ts, loc) } Instr::Hhbc(Hhbc::VerifyImplicitContextState(_)) => { // no-op Instr::tombstone() } Instr::Hhbc(Hhbc::IterFree(id, loc)) => { let lid = iter_var_name(id, &builder.strings); let value = builder.emit(Instr::Hhbc(Hhbc::CGetL(lid, loc))); builder.hhbc_builtin(hack::Hhbc::IterFree, &[value], loc) } Instr::Hhbc(Hhbc::ClassHasReifiedGenerics(..) | Hhbc::HasReifiedParent(..)) => { // Reified generics generate a lot of IR that is opaque to the analysis and actually // negatively affects the precision. Lowering these checks to a constant value // 'false' allows us to skip the whole branches related to reified generics. let value = builder.emit_constant(Constant::Bool(false)); Instr::copy(value) } Instr::Terminator(Terminator::JmpOp { cond, pred, targets: [true_bid, false_bid], loc, }) => { match lookup_constant(&builder.func, cond) { // TODO(arr): do we need to check any other known falsy/truthy values here? Some(Constant::Bool(cond)) => { let reachable_branch = if *cond && pred == Predicate::NonZero || !*cond && pred == Predicate::Zero { true_bid } else { false_bid }; Instr::Terminator(Terminator::Jmp(reachable_branch, loc)) } _ => { return instr; } } } Instr::Terminator(Terminator::IterInit(args, value)) => { self.iter_init(builder, args, value) } Instr::Terminator(Terminator::IterNext(args)) => self.iter_next(builder, args), Instr::Terminator(Terminator::MemoGet(memo)) => self.memo_get(builder, memo), Instr::Terminator(Terminator::MemoGetEager(memo)) => self.memo_get_eager(builder, memo), Instr::Terminator(Terminator::RetM(ops, loc)) => { // ret a, b; // => // ret vec[a, b]; let builtin = hack::Hhbc::NewVec; let vec = builder.emit_hhbc_builtin(builtin, &ops, loc); Instr::ret(vec, loc) } Instr::Terminator(Terminator::SSwitch { cond, cases, targets, loc, }) => { // if (StrEq(cond, case_0)) jmp targets[0]; // else if (StrEq(cond, case_1)) jmp targets[1]; // ... // else jmp targets.last(); // Last case MUST be 'default'. let iter = cases.iter().take(cases.len() - 1).zip(targets.iter()); for (case, target) in iter { let string = builder.emit_constant(Constant::String(*case)); let pred = builder.emit_hhbc_builtin(hack::Hhbc::CmpSame, &[string, cond], loc); let false_bid = builder.alloc_bid(); builder.emit(Instr::jmp_op( pred, Predicate::NonZero, *target, false_bid, loc, )); builder.start_block(false_bid); } Instr::jmp(*targets.last().unwrap(), loc) } instr => { return instr; } }; self.changed = true; instr } } fn rewrite_nullsafe_call( original_iid: InstrId, builder: &mut FuncBuilder<'_>, mut call: Call, state: &mut TransformState, ) -> Instr { // rewrite a call like `$a?->b()` into `$a ? $a->b() : null` call.detail = match call.detail { CallDetail::FCallObjMethod { .. } => CallDetail::FCallObjMethod { flavor: ObjMethodOp::NullThrows, }, CallDetail::FCallObjMethodD { method, .. } => CallDetail::FCallObjMethodD { flavor: ObjMethodOp::NullThrows, method, }, _ => unreachable!(), }; // We need to be careful about multi-return! // (ret, a, b) = obj?->call(inout a, inout b) // -> // if (obj) { // (ret, a, b) // } else { // (null, a, b) // } let loc = call.loc; let obj = call.obj(); let num_rets = call.num_rets; let pred = builder.emit_hack_builtin(hack::Builtin::Hhbc(hack::Hhbc::IsTypeNull), &[obj], loc); // Need to customize the if/then/else because of multi-return. let join_bid = builder.alloc_bid(); let null_bid = builder.alloc_bid(); let nonnull_bid = builder.alloc_bid(); builder.emit(Instr::jmp_op( pred, Predicate::NonZero, null_bid, nonnull_bid, loc, )); // Null case - main value should be null. Inouts should be passed through. builder.start_block(null_bid); let mut args = Vec::with_capacity(num_rets as usize); args.push(builder.emit_constant(Constant::Null)); if let Some(inouts) = call.inouts.as_ref() { for inout_idx in inouts.iter() { let op = call.operands[*inout_idx as usize]; args.push(op); } } builder.emit(Instr::jmp_args(join_bid, &args, loc)); // Nonnull case - make call and pass Select values. builder.start_block(nonnull_bid); args.clear(); let iid = builder.emit(Instr::Call(Box::new(call))); if num_rets > 1 { for idx in 0..num_rets { args.push(builder.emit(Instr::Special(Special::Select(iid, idx)))); } } else { args.push(iid); } builder.emit(Instr::jmp_args(join_bid, &args, loc)); // Join builder.start_block(join_bid); args.clear(); if num_rets > 1 { // we need to swap out the original Select statements. for idx in 0..num_rets { let param = builder.alloc_param(); args.push(param); state.rewrite_select_idx(original_iid, idx as usize, param); } Instr::tombstone() } else { let param = builder.alloc_param(); args.push(param); Instr::copy(args[0]) } } fn iter_var_name(id: ir::IterId, strings: &ir::StringInterner) -> LocalId { let name = strings.intern_str(format!("iter{}", id.idx)); LocalId::Named(name) } /// `is_type_struct_c` is used to type-check (among other things) against _unresolved_ but known /// class name and for `is null`/`is nonnull` checks. This transformation detects such _constant_ /// type-checks and rewrites them using a simpler form. fn rewrite_constant_type_check( builder: &mut FuncBuilder<'_>, obj: ValueId, typestruct: ValueId, loc: LocId, ) -> Option<Instr> { let typestruct = lookup_constant(&builder.func, typestruct)?; let typestruct = match typestruct { Constant::Array(tv) => TypeStruct::try_from_typed_value(tv, &builder.strings)?, _ => return None, }; match typestruct { TypeStruct::Null => Some(builder.hhbc_builtin(hack::Hhbc::IsTypeNull, &[obj], loc)), TypeStruct::Nonnull => { let is_null = builder.emit_hhbc_builtin(hack::Hhbc::IsTypeNull, &[obj], loc); Some(builder.hhbc_builtin(hack::Hhbc::Not, &[is_null], loc)) } TypeStruct::Unresolved(clsid) => { let instr = Instr::Hhbc(Hhbc::InstanceOfD(obj, clsid, loc)); Some(instr) } } }
Rust
hhvm/hphp/hack/src/hackc/ir/conversions/textual/lower/mod.rs
pub(crate) mod class; pub(crate) mod constants; pub(crate) mod func; pub(crate) mod func_builder; pub(crate) mod instrs; pub(crate) use class::lower_class; pub(crate) use func::lower_func;
Rust
hhvm/hphp/hack/src/hackc/ir/ir_core/block.rs
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. use newtype::IdVec; use crate::instr::HasOperands; use crate::BlockId; use crate::Func; use crate::Instr; use crate::InstrId; use crate::TryCatchId; use crate::ValueId; use crate::ValueIdMap; /// A Block represents a basic-block in a CFG. A well-formed Block contains zero /// or more non-terminal InstrIds followed by a terminal InstrId. The /// InstrIds refer to Instrs in the Block's Func's `Func::instrs` table. #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub struct Block { pub params: Vec<InstrId>, pub iids: Vec<InstrId>, /// A name for the Block. This is used for printing and to a minor extent /// when converting from IR to bytecode. pub pname_hint: Option<String>, /// TryCatchId for the Block. This defines which Try or Catch frame the Block /// is in. pub tcid: TryCatchId, } impl Block { /// Return an Iterator to the InstrIds that make up this Block. pub fn iids(&self) -> impl DoubleEndedIterator<Item = InstrId> + '_ { self.iids.iter().copied() } pub fn is_empty(&self) -> bool { self.iids.is_empty() } /// A well-formed Block is always terminated. This is only useful when /// building a Block. pub fn is_terminated(&self, func: &Func<'_>) -> bool { if let Some(&iid) = self.iids.last() { func.instr(iid).is_terminal() } else { false } } /// Visits all the instructions in the block and uses the `renumber` mapping /// on them. Does not renumber the instructions of the block itself. pub(crate) fn remap_vids( &mut self, instrs: &mut IdVec<InstrId, Instr>, remap: &ValueIdMap<ValueId>, ) { for iid in self.iids() { for iid2 in instrs[iid].operands_mut() { *iid2 = *remap.get(iid2).unwrap_or(iid2); } } } /// Returns the InstrId of the terminator for this Block. If the Block is /// malformed then the behavior is undefined. pub fn terminator_iid(&self) -> InstrId { self.iids .last() .copied() .unwrap_or_else(|| panic!("malformed block - empty block")) } /// Assign the name to the Block and return the Block. pub fn with_pname<T: ToString>(mut self, name: T) -> Block { self.pname_hint = Some(name.to_string()); self } } #[derive(Debug)] pub struct BlockIdIterator { pub(crate) current: BlockId, pub(crate) limit: BlockId, } impl Iterator for BlockIdIterator { type Item = BlockId; fn next(&mut self) -> Option<BlockId> { let current = self.current; if current == self.limit { None } else { self.current.0 += 1; Some(current) } } fn size_hint(&self) -> (usize, Option<usize>) { let n = self.limit.0 - self.current.0; (n as usize, Some(n as usize)) } fn nth(&mut self, n: usize) -> Option<BlockId> { let max_skip = (self.limit.0 - self.current.0) as usize; let skip = std::cmp::min(max_skip, n) as u32; self.current.0 += skip; self.next() } } impl DoubleEndedIterator for BlockIdIterator { fn next_back(&mut self) -> Option<BlockId> { let limit = self.limit; if limit == self.current { None } else { self.limit.0 -= 1; Some(BlockId(limit.0 - 1)) } } fn nth_back(&mut self, n: usize) -> Option<BlockId> { let max_skip = (self.limit.0 - self.current.0) as usize; let skip = std::cmp::min(max_skip, n) as u32; self.limit.0 -= skip; self.next_back() } } impl std::iter::ExactSizeIterator for BlockIdIterator { fn len(&self) -> usize { (self.limit.0 - self.current.0) as usize } } impl std::iter::FusedIterator for BlockIdIterator {}
TOML
hhvm/hphp/hack/src/hackc/ir/ir_core/Cargo.toml
# @generated by autocargo [package] name = "ir_core" version = "0.0.0" edition = "2021" [lib] path = "lib.rs" [dependencies] bstr = { version = "1.4.0", features = ["serde", "std", "unicode"] } ffi = { version = "0.0.0", path = "../../../utils/ffi" } hash = { version = "0.0.0", path = "../../../utils/hash" } hhbc = { version = "0.0.0", path = "../../hhbc/cargo/hhbc" } hhvm_types_ffi = { version = "0.0.0", path = "../../hhvm_cxx/hhvm_types" } indexmap = { version = "1.9.2", features = ["arbitrary", "rayon", "serde-1"] } macros = { version = "0.0.0", path = "../macros" } naming_special_names_rust = { version = "0.0.0", path = "../../../naming" } newtype = { version = "0.0.0", path = "../../../utils/newtype" } parking_lot = { version = "0.12.1", features = ["send_guard"] } smallvec = { version = "1.6.1", features = ["serde", "specialization", "union"] } strum = { version = "0.24", features = ["derive"] } [dev-dependencies] static_assertions = "1.1.0"
Rust
hhvm/hphp/hack/src/hackc/ir/ir_core/class.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use ffi::Str; use crate::func::SrcLoc; use crate::Attr; use crate::Attribute; use crate::ClassId; use crate::CtxConstant; use crate::HackConstant; use crate::Method; use crate::PropId; use crate::TraitReqKind; use crate::TypeConstant; use crate::TypeInfo; use crate::TypedValue; use crate::Visibility; /// This represents a Hack class or enum in IR. #[derive(Debug)] pub struct Class<'a> { /// Class attributes. pub attributes: Vec<Attribute>, /// Base class. pub base: Option<ClassId>, /// Class constants. pub constants: Vec<HackConstant>, // TODO: (doc coeffect constants) pub ctx_constants: Vec<CtxConstant<'a>>, /// Doc comment for the class. pub doc_comment: Option<Str<'a>>, /// In an enum this is the enum_type: /// ``` /// enum A: int as int /// ^^^ /// ``` pub enum_type: Option<TypeInfo>, pub enum_includes: Vec<ClassId>, pub flags: Attr, /// The implemented interfaces. pub implements: Vec<ClassId>, /// The methods defined in this class. pub methods: Vec<Method<'a>>, pub name: ClassId, pub properties: Vec<Property<'a>>, pub requirements: Vec<Requirement>, pub src_loc: SrcLoc, pub type_constants: Vec<TypeConstant<'a>>, /// For class generics the upper bounds of each generic. pub upper_bounds: Vec<(Str<'a>, Vec<TypeInfo>)>, pub uses: Vec<ClassId>, } impl<'a> Class<'a> { pub fn get_prop_by_pid(&self, pid: PropId) -> Option<&Property<'a>> { self.properties.iter().find(|prop| prop.name == pid) } pub fn is_trait(&self) -> bool { (self.flags & Attr::AttrTrait) == Attr::AttrTrait } } #[derive(Clone, Debug)] pub struct Property<'a> { pub name: PropId, pub flags: Attr, pub attributes: Vec<Attribute>, pub visibility: Visibility, pub initial_value: Option<TypedValue>, pub type_info: TypeInfo, pub doc_comment: ffi::Maybe<Str<'a>>, } #[derive(Debug)] pub struct Requirement { pub name: ClassId, pub kind: TraitReqKind, }
Rust
hhvm/hphp/hack/src/hackc/ir/ir_core/coeffects.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use ffi::Str; use crate::CcParam; use crate::Ctx; #[derive(Debug)] pub struct CtxConstant<'a> { pub name: Str<'a>, pub recognized: Vec<Str<'a>>, pub unrecognized: Vec<Str<'a>>, pub is_abstract: bool, } #[derive(Default, Debug)] pub struct Coeffects<'a> { pub static_coeffects: Vec<Ctx>, pub unenforced_static_coeffects: Vec<Str<'a>>, pub fun_param: Vec<u32>, pub cc_param: Vec<CcParam<'a>>, pub cc_this: Vec<CcThis<'a>>, pub cc_reified: Vec<CcReified<'a>>, pub closure_parent_scope: bool, pub generator_this: bool, pub caller: bool, } #[derive(Debug)] pub struct CcThis<'arena> { pub types: Vec<Str<'arena>>, } #[derive(Debug)] pub struct CcReified<'arena> { pub is_class: bool, pub index: u32, pub types: Vec<Str<'arena>>, }
Rust
hhvm/hphp/hack/src/hackc/ir/ir_core/common.rs
// Copyright (c) Facebook, Inc. and its affiliates. use crate::ClassId; use crate::TypedValue; /// Attributes are the bit of metadata that appears in double angle-brackets /// before a definition. They look like either raw identifiers or function /// calls. /// /// Attributes can appear on files, classes, functions, or parameters. /// /// ``` /// <<Attribute1, Attribute2(1, 2, 3)>> /// class MyAttributedClass { ... } /// ``` #[derive(Clone, Debug)] pub struct Attribute { pub name: ClassId, pub arguments: Vec<TypedValue>, }
Rust
hhvm/hphp/hack/src/hackc/ir/ir_core/constant.rs
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. use std::sync::Arc; use hhvm_types_ffi::Attr; use crate::instr::HasOperands; use crate::CollectionType; use crate::ConstId; use crate::ConstName; use crate::FloatBits; use crate::TypedValue; use crate::UnitBytesId; use crate::ValueId; /// A constant value. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum Constant<'a> { Array(Arc<TypedValue>), Bool(bool), Dir, File, Float(FloatBits), FuncCred, Int(i64), Method, Named(ConstName<'a>), NewCol(CollectionType), Null, String(UnitBytesId), Uninit, } impl HasOperands for Constant<'_> { fn operands(&self) -> &[ValueId] { // By definition constants don't have operands. &[] } fn operands_mut(&mut self) -> &mut [ValueId] { // By definition constants don't have operands. &mut [] } } #[derive(Debug)] pub struct HackConstant { pub name: ConstId, pub value: Option<TypedValue>, pub attrs: Attr, }
Rust
hhvm/hphp/hack/src/hackc/ir/ir_core/func.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use ffi::Str; use newtype::newtype_int; use newtype::IdVec; use crate::block::BlockIdIterator; use crate::instr::Terminator; use crate::Attr; use crate::Attribute; use crate::Block; use crate::BlockId; use crate::BlockIdMap; use crate::ClassId; use crate::ClassIdMap; use crate::Coeffects; use crate::Constant; use crate::ConstantId; use crate::FunctionFlags; use crate::FunctionId; use crate::HasEdges; use crate::Instr; use crate::InstrId; use crate::LocId; use crate::LocalId; use crate::MethodFlags; use crate::MethodId; use crate::TypeInfo; use crate::UnitBytesId; use crate::ValueId; use crate::ValueIdMap; use crate::Visibility; #[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)] pub struct Filename(pub UnitBytesId); impl Filename { pub const NONE: Filename = Filename(UnitBytesId::NONE); } #[derive(Clone, Debug, Default, Hash, Eq, PartialEq)] pub struct SrcLoc { pub filename: Filename, pub line_begin: i32, pub col_begin: i32, pub line_end: i32, pub col_end: i32, } impl SrcLoc { pub fn to_hhbc(&self) -> hhbc::SrcLoc { hhbc::SrcLoc { line_begin: self.line_begin, col_begin: self.col_begin, line_end: self.line_end, col_end: self.col_end, } } pub fn to_span(&self) -> hhbc::Span { hhbc::Span { line_begin: self.line_begin, line_end: self.line_end, } } pub fn from_hhbc(filename: Filename, src_loc: &hhbc::SrcLoc) -> Self { Self { filename, line_begin: src_loc.line_begin, col_begin: src_loc.col_begin, line_end: src_loc.line_end, col_end: src_loc.col_end, } } pub fn from_span(filename: Filename, span: &hhbc::Span) -> Self { Self { filename, line_begin: span.line_begin, col_begin: 0, line_end: span.line_end, col_end: 0, } } } /// Func parameters. #[derive(Clone, Debug)] pub struct Param<'a> { pub name: UnitBytesId, pub is_variadic: bool, pub is_inout: bool, pub is_readonly: bool, pub user_attributes: Vec<Attribute>, pub ty: TypeInfo, /// This is the BlockId which is the entrypoint for where initialization of /// this param begins. The string is the code string which was used to /// compile the initialization value (for reflection). /// /// For example, for the function: /// function myfn(int $a = 2 + 3) /// /// The block will initialize `$a` to 5 and the string will be "2 + 3". pub default_value: Option<DefaultValue<'a>>, } #[derive(Clone, Copy, Debug)] pub struct DefaultValue<'a> { /// What block to jump to to initialize this default value pub init: BlockId, /// Source text for the default value initializer expression (for reflection). pub expr: Str<'a>, } newtype_int!(ExFrameId, u32, ExFrameIdMap, ExFrameIdSet); /// Exception Frame State /// /// Every Block contains a TryCatchId which indicates if exceptions thrown from /// that block should be caught or not. If caught then they refer to an /// ExFrameId which tells the system where to jump on an exception. /// /// Every try/catch block is made of two sections: the 'try' section and the /// 'catch' section. Again - this could probably be computed but is easier to /// store for now. /// /// Q: Why like this and not like LLVM? /// A: LLVM does exception handling with an `invoke` instruction instead of a /// call for calls that can throw. The problem is that most HHVM instructions /// can throw whereas most LLVM instructions cannot - so everythng would need /// to be an `invoke` in that model. In addition reconstructing the HHVM /// TryBegin/TryMiddle/TryEnd model directly from the LLVM style state can be /// tricky. #[derive(Clone, Debug)] pub struct ExFrame { /// The parent of this ExFrame. The parent is probably not strictly /// necessary and could be recomputed from the try/catch structure - but /// makes generating the bytecode a little simpler for now. pub parent: TryCatchId, /// Where exceptions thrown from this block should be handled. The /// `catch_bid` should take a single Block parameter which receives the /// thrown exception. pub catch_bid: BlockId, } #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] #[derive(Default)] pub enum TryCatchId { /// This block doesn't catch exceptions. #[default] None, /// This block is part of the 'try' portion of this exception frame. Try(ExFrameId), /// This block is part of the 'catch' portion of this exception frame. Catch(ExFrameId), } impl TryCatchId { pub fn is_none(&self) -> bool { matches!(self, Self::None) } pub fn exid(&self) -> ExFrameId { match self { Self::None => ExFrameId::NONE, Self::Try(id) | Self::Catch(id) => *id, } } } /// A Func represents a body of code. It's used for both Function and Method. /// /// Code is organized into basic-Blocks which contain a series of 0 or more /// non-terminal instructions ending with a terminal instruction. /// /// A Block can take parameters which are used to pass data when control is /// transferred to the Block. /// /// - A Block can end with the ControlFlow::JmpArgs instruction to pass data /// to a successor block (these correspond to phi-nodes in the SSA graph). /// /// - A Block which is the target of exception handling will be passed the /// exception object as a Block parameter. /// /// - Async calls (Instr::CallAsync) are terminators which transfer control to /// one of two successor Blocks depending on whether the async completed /// (eager) or had to await. The eager successor is passed the call's return /// value as a Block parameter whereas the await successor is passed the /// Await object as a Block parameter. /// /// Funcs also contain some amount of storage for data associated with the code /// - such as constant values or locations - so they can referred to with /// indices instead of having to deal with refereces and ownerhip (and to make /// them smaller). /// /// Exception frames are tracked as a separate tree structure made up of Blocks. /// Each exception frame says where to jump in the case of a thrown exception. /// #[derive(Clone, Debug, Default)] pub struct Func<'a> { pub blocks: IdVec<BlockId, Block>, pub doc_comment: Option<Str<'a>>, pub ex_frames: ExFrameIdMap<ExFrame>, pub instrs: IdVec<InstrId, Instr>, pub is_memoize_wrapper: bool, pub is_memoize_wrapper_lsb: bool, pub constants: IdVec<ConstantId, Constant<'a>>, pub locs: IdVec<LocId, SrcLoc>, pub num_iters: usize, pub params: Vec<Param<'a>>, pub return_type: TypeInfo, /// shadowed_tparams are the set of tparams on a method which shadow a /// tparam on the containing class. pub shadowed_tparams: Vec<ClassId>, pub loc_id: LocId, pub tparams: ClassIdMap<TParamBounds>, } impl<'a> Func<'a> { // By definition the entry block is block zero. pub const ENTRY_BID: BlockId = BlockId(0); pub fn alloc_constant(&mut self, constant: Constant<'a>) -> ConstantId { let cid = ConstantId::from_usize(self.constants.len()); self.constants.push(constant); cid } pub fn alloc_instr(&mut self, i: Instr) -> InstrId { let iid = InstrId::from_usize(self.instrs.len()); self.instrs.push(i); iid } pub fn alloc_instr_in(&mut self, bid: BlockId, i: Instr) -> InstrId { let iid = self.alloc_instr(i); self.blocks[bid].iids.push(iid); iid } pub fn alloc_param_in(&mut self, bid: BlockId) -> InstrId { let iid = self.alloc_instr(Instr::param()); self.blocks[bid].params.push(iid); iid } pub fn alloc_bid(&mut self, block: Block) -> BlockId { let bid = BlockId::from_usize(self.blocks.len()); self.blocks.push(block); bid } pub fn block(&self, bid: BlockId) -> &Block { self.get_block(bid) .unwrap_or_else(|| panic!("{:?} not found", bid)) } pub fn block_ids(&self) -> BlockIdIterator { BlockIdIterator { current: Self::ENTRY_BID, limit: BlockId(self.blocks.len() as u32), } } pub fn block_mut(&mut self, bid: BlockId) -> &mut Block { self.blocks.get_mut(bid).unwrap() } /// Yields normal instructions in bodies (not constants or params). pub fn body_iids(&self) -> impl DoubleEndedIterator<Item = InstrId> + '_ { self.block_ids().flat_map(|bid| self.blocks[bid].iids()) } pub fn body_instrs(&self) -> impl DoubleEndedIterator<Item = &Instr> + '_ { self.body_iids().map(|iid| &self.instrs[iid]) } pub fn catch_target(&self, bid: BlockId) -> BlockId { fn get_catch_frame<'b>(func: &'b Func<'_>, tcid: TryCatchId) -> Option<&'b ExFrame> { match tcid { TryCatchId::None => None, TryCatchId::Try(exid) => Some(&func.ex_frames[&exid]), TryCatchId::Catch(exid) => { let parent = func.ex_frames[&exid].parent; get_catch_frame(func, parent) } } } let tcid = self.block(bid).tcid; if let Some(frame) = get_catch_frame(self, tcid) { frame.catch_bid } else { BlockId::NONE } } pub fn constant(&self, cid: ConstantId) -> &Constant<'a> { self.get_constant(cid).unwrap() } pub fn edges(&self, bid: BlockId) -> &[BlockId] { self.terminator(bid).edges() } pub fn edges_mut(&mut self, bid: BlockId) -> &mut [BlockId] { self.terminator_mut(bid).edges_mut() } pub fn emit(&mut self, bid: BlockId, instr: Instr) -> ValueId { let iid = self.alloc_instr(instr); self.block_mut(bid).iids.push(iid); ValueId::from_instr(iid) } pub fn get_block(&self, bid: BlockId) -> Option<&Block> { self.blocks.get(bid) } pub fn get_constant(&self, cid: ConstantId) -> Option<&Constant<'a>> { self.constants.get(cid) } pub fn get_edges(&self, bid: BlockId) -> Option<&[BlockId]> { self.get_terminator(bid).map(|instr| instr.edges()) } pub fn get_instr(&self, iid: InstrId) -> Option<&Instr> { self.instrs.get(iid) } pub fn get_instr_mut(&mut self, iid: InstrId) -> Option<&mut Instr> { self.instrs.get_mut(iid) } pub fn get_param_by_lid(&self, lid: LocalId) -> Option<&Param<'_>> { match lid { LocalId::Named(name) => self.params.iter().find(|p| p.name == name), LocalId::Unnamed(_) => None, } } pub fn get_loc(&self, loc: LocId) -> Option<&SrcLoc> { self.locs.get(loc) } pub fn get_terminator(&self, bid: BlockId) -> Option<&Terminator> { let block = self.block(bid); let iid = *block.iids.last()?; let instr = self.get_instr(iid)?; match instr { Instr::Terminator(terminator) => Some(terminator), _ => None, } } pub fn instr(&self, iid: InstrId) -> &Instr { self.get_instr(iid).unwrap() } pub fn instrs_len(&self) -> usize { self.instrs.len() } pub fn instr_mut(&mut self, iid: InstrId) -> &mut Instr { self.get_instr_mut(iid).unwrap() } pub fn is_empty(&self, bid: BlockId) -> bool { self.block(bid).is_empty() } pub fn is_terminated(&self, bid: BlockId) -> bool { self.block(bid).is_terminated(self) } pub fn is_terminal(&self, vid: ValueId) -> bool { vid.instr() .map_or(false, |iid| self.instr(iid).is_terminal()) } pub fn loc(&self, loc: LocId) -> &SrcLoc { assert!(loc != LocId::NONE); self.get_loc(loc).unwrap() } // Visits all the instructions in the block and uses the `remap` mapping on // them. Does not renumber the instructions of the block itself. pub fn remap_block_vids(&mut self, bid: BlockId, remap: &ValueIdMap<ValueId>) { let block = self.blocks.get_mut(bid).unwrap(); block.remap_vids(&mut self.instrs, remap) } // Rewrite instructions using the remap mapping. Won't renumber the // instructions themselves (so a remapping with %1 -> %2 won't remap // instruction %1 to %2, just references to %1 will be remapped to %2). pub fn remap_vids(&mut self, remap: &ValueIdMap<ValueId>) { for bid in self.block_ids() { self.remap_block_vids(bid, remap); } } /// Rewrite BlockIds using the remap remapping. Won't renumber the blocks /// themselves (so a remapping with b1 -> b2 won't remap block b1 to b2, /// just references to b1 will be remapped to b2). pub fn remap_bids(&mut self, remap: &BlockIdMap<BlockId>) { for param in &mut self.params { if let Some(dv) = param.default_value.as_mut() { dv.init = remap.get(&dv.init).copied().unwrap_or(dv.init); } } for instr in self.instrs.iter_mut() { for bid in instr.edges_mut() { *bid = remap.get(bid).copied().unwrap_or(*bid); } } } pub fn terminator(&self, bid: BlockId) -> &Terminator { let iid = self.block(bid).terminator_iid(); match self.instr(iid) { Instr::Terminator(terminator) => terminator, _ => panic!("Non-Terminator found in terminator location {}", iid), } } pub fn terminator_mut(&mut self, bid: BlockId) -> &mut Terminator { let iid = self.block(bid).terminator_iid(); match self.instr_mut(iid) { Instr::Terminator(terminator) => terminator, _ => panic!("Non-Terminator found in terminator location {}", iid), } } } /// A top-level Hack function. #[derive(Debug)] pub struct Function<'a> { pub attributes: Vec<Attribute>, pub attrs: Attr, pub coeffects: Coeffects<'a>, pub flags: FunctionFlags, pub name: FunctionId, pub func: Func<'a>, } /// A Hack method contained within a Class. #[derive(Debug)] pub struct Method<'a> { pub attributes: Vec<Attribute>, pub attrs: Attr, pub coeffects: Coeffects<'a>, pub flags: MethodFlags, pub func: Func<'a>, pub name: MethodId, pub visibility: Visibility, } #[derive(Clone, Debug, Default)] pub struct TParamBounds { pub bounds: Vec<TypeInfo>, }
Rust
hhvm/hphp/hack/src/hackc/ir/ir_core/func_builder.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::sync::Arc; use hash::HashMap; use crate::func::SrcLoc; use crate::instr::BaseOp; use crate::instr::FinalOp; use crate::instr::HasLoc; use crate::instr::HasOperands; use crate::instr::Hhbc; use crate::instr::IntermediateOp; use crate::instr::MemberKey; use crate::instr::MemberOp; use crate::instr::Special; use crate::Block; use crate::BlockId; use crate::Constant; use crate::ConstantId; use crate::Func; use crate::Instr; use crate::InstrId; use crate::InstrIdMap; use crate::LocId; use crate::LocalId; use crate::MOpMode; use crate::PropId; use crate::QueryMOp; use crate::ReadonlyOp; use crate::StringInterner; use crate::ValueId; pub struct FuncBuilder<'a> { pub func: Func<'a>, pub strings: Arc<StringInterner>, cur_bid: BlockId, pub loc_lookup: HashMap<SrcLoc, LocId>, pub constant_lookup: HashMap<Constant<'a>, ConstantId>, block_rewrite_stopped: bool, changed: bool, /// Used with rewrite_block(), maps old InstrId -> new InstrId, to handle /// replacing one instr with another. /// /// For example, if we fold "add 2,2" => "4", and a Constant for 4 already exists, we will /// redirect all references to the add's InstrId to use 4's ID instead. This is effectively /// on-the-fly copy propagation. /// /// InstrIds not in this table implicitly map to themselves, so the table is only populated /// at all once a remapping is needed. InstrIds in this table may or may not map to /// themselves. replacements: InstrIdMap<ValueId>, } impl<'a> FuncBuilder<'a> { pub fn build_func<F>(strings: Arc<StringInterner>, f: F) -> Func<'a> where F: FnOnce(&mut FuncBuilder<'a>), { let mut builder = FuncBuilder::with_func(Func::default(), strings); builder.cur_bid = builder.alloc_bid(); f(&mut builder); builder.finish() } /// Create a FuncBuilder to edit a Func. If the caller can guarantee that no /// strings will be created (in an RPO pass which just re-orders blocks, for /// example) then it can create and pass in a /// StringInterner::read_only(). pub fn with_func(func: Func<'a>, strings: Arc<StringInterner>) -> Self { let constant_lookup: HashMap<Constant<'a>, ConstantId> = func .constants .iter() .enumerate() .map(|(idx, constant)| (constant.clone(), ConstantId::from_usize(idx))) .collect(); let loc_lookup: HashMap<SrcLoc, LocId> = func .locs .iter() .enumerate() .map(|(idx, loc)| (loc.clone(), LocId::from_usize(idx))) .collect(); FuncBuilder { block_rewrite_stopped: false, changed: false, constant_lookup, cur_bid: BlockId::NONE, func, loc_lookup, replacements: Default::default(), strings, } } /// Similar to with_func() but borrows the Func instead of owning it. pub fn borrow_func<F, R>(borrowed: &mut Func<'a>, strings: Arc<StringInterner>, f: F) -> R where F: FnOnce(&mut FuncBuilder<'a>) -> R, { let func = std::mem::take(borrowed); let mut builder = FuncBuilder::with_func(func, strings); let r = f(&mut builder); *borrowed = builder.finish(); r } /// Similar to borrow_func() but for a builder that doesn't need the /// StringInterner. A temporary StringInterner is used and checked when the /// handler returns. If any strings were interned during the call a panic is /// raised. pub fn borrow_func_no_strings<F, R>(borrowed: &mut Func<'a>, f: F) -> R where F: FnOnce(&mut FuncBuilder<'a>) -> R, { let tmp_strings = Arc::new(StringInterner::read_only()); Self::borrow_func(borrowed, tmp_strings, f) } pub fn add_loc(&mut self, loc: SrcLoc) -> LocId { use std::collections::hash_map::Entry; match self.loc_lookup.entry(loc) { Entry::Occupied(e) => *e.get(), Entry::Vacant(e) => { let id = LocId::from_usize(self.func.locs.len()); self.func.locs.push(e.key().clone()); e.insert(id); id } } } pub fn alloc_bid(&mut self) -> BlockId { let bid = BlockId::from_usize(self.func.blocks.len()); self.func.blocks.push(Block::default()); bid } pub fn cur_bid(&self) -> BlockId { self.cur_bid } pub fn cur_block(&self) -> &Block { &self.func.blocks[self.cur_bid] } pub fn cur_block_mut(&mut self) -> &mut Block { &mut self.func.blocks[self.cur_bid] } pub fn alloc_param(&mut self) -> ValueId { let iid = self.func.alloc_param_in(self.cur_bid); ValueId::from_instr(iid) } pub fn emit(&mut self, i: Instr) -> ValueId { assert!(!i.is_param()); let iid = self.func.alloc_instr_in(self.cur_bid, i); ValueId::from_instr(iid) } pub fn emit_constant(&mut self, constant: Constant<'a>) -> ValueId { let lit_id = self .constant_lookup .entry(constant) .or_insert_with_key(|constant| self.func.alloc_constant(constant.clone())); ValueId::from_constant(*lit_id) } pub fn finish(self) -> Func<'a> { let mut func = self.func; while !func.blocks.is_empty() { let bid = BlockId::from_usize(func.blocks.len() - 1); if func.blocks[bid].iids.is_empty() { func.blocks.pop(); } else { break; } } func } pub fn start_block(&mut self, bid: BlockId) { self.cur_bid = bid; } /// Walk through the block calling transformer.apply() on each Instr. pub fn rewrite_block(&mut self, bid: BlockId, transformer: &mut dyn TransformInstr) { // Steal the block contents so we can loop through them without a func // borrow, and clear the old block's body so we can append to it as we // go. let rb = &mut self.func.blocks[bid]; let rb_len = rb.iids.len(); let block_snapshot = std::mem::replace(&mut rb.iids, Vec::with_capacity(rb_len)); // Process the block. self.cur_bid = bid; self.block_rewrite_stopped = false; let mut state = TransformState::new(); for iid in block_snapshot { self.rewrite_instr(iid, transformer, &mut state); if self.block_rewrite_stopped { break; } } self.cur_bid = BlockId::NONE; } /// Cause the block rewrite loop to "break" once the current instr is /// finished. pub fn stop_block_rewrite(&mut self) { self.block_rewrite_stopped = true; } fn rewrite_instr( &mut self, iid: InstrId, transformer: &mut dyn TransformInstr, state: &mut TransformState, ) { // Temporarily steal from the func the instr we want to transform, so we // can manipulate it without borrowing the func. If we borrow it, we // wouldn't be able to create new instrs as part of the transformation. // // Swapping in a tombstone solves this problem and avoids needing to // clone(). The tombstone instr being there temporarily is OK because // we know nothing will look it up (although they technically could). let mut instr = std::mem::replace(&mut self.func.instrs[iid], Instr::tombstone()); // Snap through any relaced instrs to the real value. self.replace_operands(&mut instr); let output = match instr { Instr::Special(Special::Select(src, idx)) => { let src = src.expect_instr("instr expected"); self.rewrite_select(iid, instr, src, idx, state) } _ => transformer.apply(iid, instr, self, state), }; // Apply the transformation and learn what to do with the result. match output { Instr::Special(Special::Copy(value)) => { // Do copy-propagation on the fly, emitting nothing to the block. self.changed = true; self.replace(iid, value); } Instr::Special(Special::Tombstone) => {} other => { self.func.instrs[iid] = other; self.func.blocks[self.cur_bid].iids.push(iid); } } } fn num_selects(instr: &Instr) -> u32 { let num_rets = match instr { Instr::Call(call) => call.num_rets, Instr::Hhbc(Hhbc::ClassGetTS(..)) => 2, Instr::MemberOp(ref op) => op.num_values() as u32, _ => 1, }; if num_rets > 1 { num_rets } else { 0 } } fn rewrite_select( &mut self, iid: InstrId, instr: Instr, src: InstrId, idx: u32, state: &mut TransformState, ) -> Instr { if let Some(dst) = state.select_mapping.get(&iid) { // This acts like the Select was just replaced by Instr::copy(). return Instr::copy(*dst); } if iid == InstrId::from_usize(src.as_usize() + 1 + idx as usize) { if idx < Self::num_selects(&self.func.instrs[src]) { // If the rewriter didn't do anything interesting with the // original Instr then we just want to keep the Select // as-is. return instr; } } panic!("Un-rewritten Select: InstrId {iid:?} ({instr:?})"); } /// If iid has been replaced with another InstrId, return that, else return vid. pub fn find_replacement(&mut self, vid: ValueId) -> ValueId { let replacements = &mut self.replacements; if let Some(iid) = vid.instr() { if let Some(&replacement) = replacements.get(&iid) { // We found a replacement (rare), so go ahead and do the extra work of // following and optimizing the replacement chain. let mut prev = iid; let mut cur = replacement; while let Some(&next) = cur.instr().and_then(|cur| replacements.get(&cur)) { // This is a multi-hop chain (very rare). // // At this point we have the chain: prev -> cur -> next. // Shorten it as in union-find path splitting to speed // future lookups by making prev point directly to next. replacements.insert(prev, next); prev = cur.expect_instr("not instr"); cur = next; } cur } else { vid } } else { vid } } /// Apply substitutions requested by replace() to each operand. pub fn replace_operands(&mut self, instr: &mut Instr) { if !self.replacements.is_empty() { for iid in instr.operands_mut() { let new = self.find_replacement(*iid); if *iid != new { self.changed = true; *iid = new; } } } } /// Indicate that during a rewrite all references to old_iid should be /// replaced with new_vid. /// /// NOTE: This does not set self.changed = true, because simply indicating /// that references to a dead instr should be replaced doesn't actually change /// the function. pub fn replace(&mut self, old_iid: InstrId, new_vid: ValueId) { if ValueId::from_instr(old_iid) != new_vid { self.replacements.insert(old_iid, new_vid); } } } /// Trait for instruction rewriters. pub trait TransformInstr { /// Optionally transform the given Instr (e.g. constant-fold) and return the /// Instr that should be used instead. This is called by /// FuncBuilder::rewrite_block which visits each instr in a block and /// transforms it. /// /// Note that when apply() is called, the FuncBuilder has temporarily /// swapped an instr::tombstone() into the func.instrs slot being /// transformed. /// /// Some notable return values: /// /// - Returning instr::tombstone() indicates that FuncBuilder should do /// nothing further, including appending no instr to the current block /// being rewritten. This is typically used when an instr should be /// discarded. However it can also be used in any situation when the /// callee knows what it is doing and doesn't want the FuncBuilder to do /// anything further. This can include manually replacing the tombstone in /// func.instrs[iid] with something else. /// /// - Returning a Copy instr will actually emit nothing and get /// copy-propagated into later instrs, which is usually what you want, so /// chains of simplifications can all happen in a single pass. If you /// really want to emit an actual Copy instr for some reason you can /// record one in func.instrs[iid], append iid to the block, then return /// instr::tombstone(). Returning a Copy automatically sets rw.changed = /// true. /// /// - Any other instr is recorded in func.instrs[iid] and iid is appended to /// the current block being built up. fn apply<'a>( &mut self, iid: InstrId, instr: Instr, builder: &mut FuncBuilder<'a>, state: &mut TransformState, ) -> Instr; } /// Helper for TransformInstr pub struct TransformState { select_mapping: InstrIdMap<ValueId>, } impl TransformState { fn new() -> Self { TransformState { select_mapping: Default::default(), } } /// When rewriting an Instr that returns multiple values it is required to /// call this function to rewrite the multiple return values. The inputs to /// this function are the InstrId of the Instr::Special(Special::Select(..)). pub fn rewrite_select(&mut self, src: InstrId, dst: ValueId) { assert!(!self.select_mapping.contains_key(&src)); self.select_mapping.insert(src, dst); } /// Like rewrite_select() this is used to note multiple return values - but /// uses the InstrId of the original instruction (not the Select) and a /// Select index. pub fn rewrite_select_idx(&mut self, src_iid: InstrId, src_idx: usize, dst_vid: ValueId) { self.rewrite_select( InstrId::from_usize(src_iid.as_usize() + 1 + src_idx), dst_vid, ); } } /// Used like: /// let vid = MemberOpBuilder::base_c(vid1, loc).emit_query_ec(builder, vid2); pub struct MemberOpBuilder { pub operands: Vec<ValueId>, pub locals: Vec<LocalId>, pub base_op: BaseOp, pub intermediate_ops: Vec<IntermediateOp>, } impl MemberOpBuilder { // There are a lot of unhandled operations here - feel free to extend as // necessary... fn new(base_op: BaseOp) -> MemberOpBuilder { MemberOpBuilder { operands: Default::default(), locals: Default::default(), base_op, intermediate_ops: Default::default(), } } pub fn final_op(self, final_op: FinalOp) -> MemberOp { MemberOp { operands: self.operands.into_boxed_slice(), locals: self.locals.into_boxed_slice(), base_op: self.base_op, intermediate_ops: self.intermediate_ops.into_boxed_slice(), final_op, } } pub fn base_c(base: ValueId, loc: LocId) -> Self { let mode = MOpMode::None; let mut mop = Self::new(BaseOp::BaseC { mode, loc }); mop.operands.push(base); mop } pub fn base_h(loc: LocId) -> Self { Self::new(BaseOp::BaseH { loc }) } pub fn base_st( base: ValueId, prop: PropId, mode: MOpMode, readonly: ReadonlyOp, loc: LocId, ) -> Self { let mut mop = Self::new(BaseOp::BaseST { mode, readonly, loc, prop, }); mop.operands.push(base); mop } pub fn isset_ec(mut self, key: ValueId) -> MemberOp { self.operands.push(key); let loc = self.base_op.loc_id(); self.final_op(FinalOp::QueryM { key: MemberKey::EC, readonly: ReadonlyOp::Any, query_m_op: QueryMOp::Isset, loc, }) } pub fn emit_isset_ec(self, builder: &mut FuncBuilder<'_>, key: ValueId) -> ValueId { let mop = self.isset_ec(key); builder.emit(Instr::MemberOp(mop)) } pub fn query_ec(mut self, key: ValueId) -> MemberOp { self.operands.push(key); let loc = self.base_op.loc_id(); self.final_op(FinalOp::QueryM { key: MemberKey::EC, readonly: ReadonlyOp::Any, query_m_op: QueryMOp::CGet, loc, }) } pub fn emit_query_ec(self, builder: &mut FuncBuilder<'_>, key: ValueId) -> ValueId { let mop = self.query_ec(key); builder.emit(Instr::MemberOp(mop)) } pub fn query_pt(self, key: PropId) -> MemberOp { let loc = self.base_op.loc_id(); self.final_op(FinalOp::QueryM { key: MemberKey::PT(key), readonly: ReadonlyOp::Any, query_m_op: QueryMOp::CGet, loc, }) } pub fn emit_query_pt(self, builder: &mut FuncBuilder<'_>, key: PropId) -> ValueId { let mop = self.query_pt(key); builder.emit(Instr::MemberOp(mop)) } pub fn set_m_pt(mut self, key: PropId, value: ValueId) -> MemberOp { let loc = self.base_op.loc_id(); let key = MemberKey::PT(key); let readonly = ReadonlyOp::Any; self.operands.push(value); self.final_op(FinalOp::SetM { key, readonly, loc }) } pub fn emit_set_m_pt( self, builder: &mut FuncBuilder<'_>, key: PropId, value: ValueId, ) -> ValueId { let mop = self.set_m_pt(key, value); builder.emit(Instr::MemberOp(mop)) } }
Rust
hhvm/hphp/hack/src/hackc/ir/ir_core/func_builder_ex.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::sync::Arc; use crate::instr::Hhbc; use crate::instr::Predicate; use crate::type_struct::TypeStruct; use crate::BaseType; use crate::Constant; use crate::EnforceableType; use crate::FuncBuilder; use crate::Instr; use crate::IsTypeOp; use crate::LocId; use crate::TypeConstraintFlags; use crate::TypeStructResolveOp; use crate::ValueId; /// Helpers for emitting more complex constructs. pub trait FuncBuilderEx { /// Build an if/then: /// jmp_t true_br, false_br /// true_br: /// f() /// jmp false_br /// false_br: /// fn emit_if_then(&mut self, pred: ValueId, loc: LocId, f: impl FnOnce(&mut Self)); /// Build a conditional: /// pred ? b() : c() /// /// Note that although the callback only returns a single Instr it can emit /// as many instrs as it wants simply returning the final one. In addition /// it can return a tombstone to indicate that it already emitted everything /// it needed. fn emit_if_then_else( &mut self, pred: ValueId, loc: LocId, f_true: impl FnOnce(&mut Self) -> Instr, f_false: impl FnOnce(&mut Self) -> Instr, ) -> ValueId; /// Emit a constant string. fn emit_string(&mut self, s: &str) -> ValueId; /// Build an `is` check. fn is(&mut self, vid: ValueId, ty: &EnforceableType, loc: LocId) -> Instr; /// Emit an `is` check. This behaves like `is()` but instead of returning /// the final Instr it emits it. fn emit_is(&mut self, vid: ValueId, ty: &EnforceableType, loc: LocId) -> ValueId; } impl<'a> FuncBuilderEx for FuncBuilder<'a> { fn emit_if_then(&mut self, pred: ValueId, loc: LocId, f: impl FnOnce(&mut Self)) { let join_bid = self.alloc_bid(); let true_bid = self.alloc_bid(); self.emit(Instr::jmp_op( pred, Predicate::NonZero, true_bid, join_bid, loc, )); self.start_block(true_bid); f(self); if !self.func.is_terminated(self.cur_bid()) { self.emit(Instr::jmp(join_bid, loc)); } self.start_block(join_bid); } fn emit_if_then_else( &mut self, pred: ValueId, loc: LocId, f_true: impl FnOnce(&mut Self) -> Instr, f_false: impl FnOnce(&mut Self) -> Instr, ) -> ValueId { // b_true: // arg = f_true() // jmp b_join(arg) // b_false: // arg = f_false() // jmp b_join(arg) // b_join(arg): let mut join_bid = None; let true_bid = self.alloc_bid(); let false_bid = self.alloc_bid(); self.emit(Instr::jmp_op( pred, Predicate::NonZero, true_bid, false_bid, loc, )); self.start_block(true_bid); let instr = f_true(self); if !instr.is_tombstone() { let terminated = matches!(instr, Instr::Terminator(_)); let arg = self.emit(instr); if !terminated { let target = self.alloc_bid(); join_bid = Some(target); self.emit(Instr::jmp_args(target, &[arg], loc)); } } self.start_block(false_bid); let instr = f_false(self); if !instr.is_tombstone() { let terminated = matches!(instr, Instr::Terminator(_)); let arg = self.emit(instr); if !terminated { let target = join_bid.get_or_insert_with(|| self.alloc_bid()); self.emit(Instr::jmp_args(*target, &[arg], loc)); } } if let Some(join_bid) = join_bid { self.start_block(join_bid); self.alloc_param() } else { ValueId::none() } } fn emit_string(&mut self, s: &str) -> ValueId { self.emit_constant(Constant::String(self.strings.intern_str(s))) } fn is(&mut self, vid: ValueId, ety: &EnforceableType, loc: LocId) -> Instr { let mut modifiers = ety.modifiers; if modifiers.contains(TypeConstraintFlags::Nullable) { let is1 = self.is(vid, &EnforceableType::null(), loc); let is1 = self.emit(is1); let ety = EnforceableType { ty: ety.ty, modifiers: modifiers - TypeConstraintFlags::Nullable - TypeConstraintFlags::DisplayNullable, }; return Instr::copy(self.emit_if_then_else( is1, loc, |builder| Instr::copy(builder.emit_constant(Constant::Bool(true))), |builder| builder.is(vid, &ety, loc), )); } // (I think) ExtendedHint is used to enable non-PHP type flags - which // is now standard so we can just ignore it. modifiers -= TypeConstraintFlags::ExtendedHint; // We're just trying to do an 'is' check - we don't care if the context // is a TypeConstant. modifiers -= TypeConstraintFlags::TypeConstant; if modifiers == TypeConstraintFlags::NoFlags { fn is_type_op(op: IsTypeOp, vid: ValueId, loc: LocId) -> Instr { Instr::Hhbc(Hhbc::IsTypeC(vid, op, loc)) } fn is_type_op2( op1: IsTypeOp, op2: IsTypeOp, builder: &mut FuncBuilder<'_>, vid: ValueId, loc: LocId, ) -> Instr { let is1 = builder.emit(is_type_op(op1, vid, loc)); Instr::copy(builder.emit_if_then_else( is1, loc, |builder| Instr::copy(builder.emit_constant(Constant::Bool(true))), |_| is_type_op(op2, vid, loc), )) } match ety.ty { BaseType::AnyArray => is_type_op(IsTypeOp::ArrLike, vid, loc), BaseType::Arraykey => is_type_op2(IsTypeOp::Str, IsTypeOp::Int, self, vid, loc), BaseType::Bool => is_type_op(IsTypeOp::Bool, vid, loc), BaseType::Classname => is_type_op(IsTypeOp::Class, vid, loc), BaseType::Darray => is_type_op(IsTypeOp::Dict, vid, loc), BaseType::Dict => is_type_op(IsTypeOp::Dict, vid, loc), BaseType::Float => is_type_op(IsTypeOp::Dbl, vid, loc), BaseType::Int => is_type_op(IsTypeOp::Int, vid, loc), BaseType::Keyset => is_type_op(IsTypeOp::Keyset, vid, loc), BaseType::Mixed | BaseType::None => { Instr::copy(self.emit_constant(Constant::Bool(true))) } BaseType::Nothing => Instr::copy(self.emit_constant(Constant::Bool(false))), BaseType::Null => is_type_op(IsTypeOp::Null, vid, loc), BaseType::Num => is_type_op2(IsTypeOp::Int, IsTypeOp::Dbl, self, vid, loc), BaseType::Resource => is_type_op(IsTypeOp::Res, vid, loc), BaseType::String => is_type_op(IsTypeOp::Str, vid, loc), BaseType::This => Instr::Hhbc(Hhbc::IsLateBoundCls(vid, loc)), BaseType::Varray => is_type_op(IsTypeOp::Vec, vid, loc), BaseType::VarrayOrDarray => { is_type_op2(IsTypeOp::Dict, IsTypeOp::Vec, self, vid, loc) } BaseType::Vec => is_type_op(IsTypeOp::Vec, vid, loc), BaseType::VecOrDict => is_type_op(IsTypeOp::Dict, vid, loc), BaseType::Class(cid) => { let constant = Constant::Array(Arc::new( TypeStruct::Unresolved(cid).into_typed_value(&self.strings), )); let adata = self.emit_constant(constant); Instr::Hhbc(Hhbc::IsTypeStructC( [vid, adata], TypeStructResolveOp::Resolve, loc, )) } BaseType::Nonnull => { let iid = self.emit(Instr::Hhbc(Hhbc::IsTypeC(vid, IsTypeOp::Null, loc))); Instr::Hhbc(Hhbc::Not(iid, loc)) } BaseType::Noreturn => panic!("Unable to perform 'is' on 'noreturn'"), BaseType::Typename => panic!("Unable to perform 'is' on 'typename'"), BaseType::Void => panic!("Unable to perform 'is' on 'void'"), } } else { todo!("Unhandled modifiers: {:?}", modifiers); } } fn emit_is(&mut self, vid: ValueId, ty: &EnforceableType, loc: LocId) -> ValueId { let instr = self.is(vid, ty, loc); self.emit(instr) } }
Rust
hhvm/hphp/hack/src/hackc/ir/ir_core/instr.rs
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. use std::borrow::Cow; use macros::HasLoc; use macros::HasLocals; use macros::HasOperands; use newtype::newtype_int; use smallvec::SmallVec; use strum::Display; use crate::BareThisOp; use crate::BlockId; use crate::ClassId; use crate::CollectionType; use crate::ConstId; use crate::ContCheckOp; use crate::FCallArgsFlags; use crate::FatalOp; use crate::FunctionId; use crate::GlobalId; use crate::IncDecOp; use crate::InitPropOp; use crate::IsLogAsDynamicCallOp; use crate::IsTypeOp; use crate::IterId; use crate::LocId; use crate::MOpMode; use crate::MethodId; use crate::OODeclExistsOp; use crate::ObjMethodOp; use crate::PropId; use crate::QueryMOp; use crate::ReadonlyOp; use crate::SetOpOp; use crate::SetRangeOp; use crate::SilenceOp; use crate::SpecialClsRef; use crate::SwitchKind; use crate::TypeStructResolveOp; use crate::UnitBytesId; use crate::ValueId; use crate::VarId; pub trait HasLoc { fn loc_id(&self) -> LocId; } pub trait HasLocals { fn locals(&self) -> &[LocalId]; } pub trait HasOperands { fn operands(&self) -> &[ValueId]; fn operands_mut(&mut self) -> &mut [ValueId]; } pub trait HasEdges { fn edges(&self) -> &[BlockId]; fn edges_mut(&mut self) -> &mut [BlockId]; } pub trait CanThrow { fn can_throw(&self) -> bool; } /// Some of the Instr layouts are a little unnatural - but there are a few /// important considerations: /// /// 1. All operands must be in a layout that can be returned as a single slice /// by the operands() and operands_mut() methods. /// /// 2. All edges must be in a layout that can be returned as a single slice by /// the edges() and edges_mut() methods. /// /// 3. The internal size of Instrs should be big enough that most of the /// instructions have no external references but small enough that we're /// not wasting a ton of space on every instruction. /// /// FIXME: Right now the size is pretty big (56 bytes). For most instructions /// the bulk of this seems to be from padding. /// /// FIXME: Right now there are no types on these instructions - there really /// should be. Q: Should the type be on the Instr itself or embedded in the /// Func::instrs table? /// #[derive(Clone, Debug, HasLoc, HasLocals, HasOperands, PartialEq, Eq)] pub enum Instr { Call(Box<Call>), Hhbc(Hhbc), MemberOp(MemberOp), Special(Special), Terminator(Terminator), } impl Instr { pub fn is_param(&self) -> bool { matches!(self, Instr::Special(Special::Param)) } pub fn is_terminal(&self) -> bool { matches!(self, Instr::Terminator(_)) } pub fn is_tombstone(&self) -> bool { matches!(self, Instr::Special(Special::Tombstone)) } pub fn is_select(&self) -> bool { matches!(self, Instr::Special(Special::Select(..))) } } impl HasEdges for Instr { fn edges(&self) -> &[BlockId] { match self { Instr::Terminator(t) => t.edges(), _ => &[], } } fn edges_mut(&mut self) -> &mut [BlockId] { match self { Instr::Terminator(t) => t.edges_mut(), _ => &mut [], } } } impl CanThrow for Instr { fn can_throw(&self) -> bool { match self { Instr::Call(call) => call.can_throw(), Instr::Hhbc(hhbc) => hhbc.can_throw(), Instr::MemberOp(_) => true, Instr::Special(sp) => sp.can_throw(), Instr::Terminator(t) => t.can_throw(), } } } #[derive(Clone, Debug, HasLoc, HasLocals, HasOperands, Display, PartialEq, Eq)] pub enum Terminator { // This is an async call - it's a terminator with one edge for the async // return and one edge for the eager return. The async edge takes a single // argument which is the function's async value. The eager edge takes a // single argument which is the function's return value. CallAsync(Box<Call>, [BlockId; 2]), #[has_operands(none)] Enter(BlockId, LocId), Exit(ValueId, LocId), Fatal(ValueId, FatalOp, LocId), IterInit(IteratorArgs, ValueId), #[has_operands(none)] IterNext(IteratorArgs), #[has_operands(none)] Jmp(BlockId, LocId), JmpArgs(BlockId, Box<[ValueId]>, LocId), JmpOp { cond: ValueId, pred: Predicate, targets: [BlockId; 2], loc: LocId, }, // Hmm - should this be the range or should we explicitly list all the // locals in range so there's no question... // Reasons to make a list: // - Then you have a slice of operands like every other instruction, no more // special case. // Reason to not make a list: // - Lowering to hhbc will be harder because the locals may not be // contiguous the way hhbc needs them. #[has_operands(none)] MemoGet(MemoGet), #[has_operands(none)] MemoGetEager(MemoGetEager), NativeImpl(LocId), Ret(ValueId, LocId), RetCSuspended(ValueId, LocId), RetM(Box<[ValueId]>, LocId), #[has_locals(none)] Switch { cond: ValueId, bounded: SwitchKind, base: i64, targets: Box<[BlockId]>, loc: LocId, }, SSwitch { cond: ValueId, cases: Box<[UnitBytesId]>, targets: Box<[BlockId]>, loc: LocId, }, Throw(ValueId, LocId), ThrowAsTypeStructException([ValueId; 2], LocId), Unreachable, } impl Terminator { // Some instructions produce an 'implied' value on some edges - for example // a CallAsync will pass a value to each of its edges, but a MemoGet will // only pass a value on a single edge. This returns the number of implied // args passed along the given edge. pub fn implied_arg_count(&self, target: BlockId) -> usize { match self { Terminator::CallAsync(call, edges) => { if edges[0] == target { call.num_rets as usize } else if edges[1] == target { 1 } else { panic!("unknown target in instr"); } } Terminator::MemoGet(get) => { if get.no_value_edge() == target { 0 } else { 1 } } Terminator::MemoGetEager(get) => { if get.no_value_edge() == target { 0 } else { 1 } } _ => 0, } } } impl HasEdges for Terminator { fn edges(&self) -> &[BlockId] { match self { Terminator::CallAsync(_, targets) | Terminator::IterInit(IteratorArgs { targets, .. }, _) | Terminator::IterNext(IteratorArgs { targets, .. }) | Terminator::JmpOp { targets, .. } => targets, Terminator::Switch { targets, .. } | Terminator::SSwitch { targets, .. } => targets, Terminator::Exit(..) | Terminator::Fatal(..) | Terminator::NativeImpl(..) | Terminator::Ret(..) | Terminator::RetCSuspended(..) | Terminator::RetM(..) | Terminator::Throw(..) | Terminator::ThrowAsTypeStructException(..) | Terminator::Unreachable => &[], Terminator::Enter(bid, _) | Terminator::Jmp(bid, _) | Terminator::JmpArgs(bid, _, _) => std::slice::from_ref(bid), Terminator::MemoGet(get) => get.edges(), Terminator::MemoGetEager(get) => get.edges(), } } fn edges_mut(&mut self) -> &mut [BlockId] { match self { Terminator::CallAsync(_, targets) | Terminator::IterInit(IteratorArgs { targets, .. }, _) | Terminator::IterNext(IteratorArgs { targets, .. }) | Terminator::JmpOp { targets, .. } => targets, Terminator::Switch { targets, .. } | Terminator::SSwitch { targets, .. } => targets, Terminator::Exit(..) | Terminator::Fatal(..) | Terminator::NativeImpl(..) | Terminator::Ret(..) | Terminator::RetCSuspended(..) | Terminator::RetM(..) | Terminator::Throw(..) | Terminator::ThrowAsTypeStructException(..) | Terminator::Unreachable => &mut [], Terminator::Enter(bid, _) | Terminator::Jmp(bid, _) | Terminator::JmpArgs(bid, _, _) => std::slice::from_mut(bid), Terminator::MemoGet(get) => get.edges_mut(), Terminator::MemoGetEager(get) => get.edges_mut(), } } } impl CanThrow for Terminator { fn can_throw(&self) -> bool { match self { Terminator::CallAsync(call, _) => call.can_throw(), Terminator::Enter(..) | Terminator::Exit(..) | Terminator::Jmp(..) | Terminator::JmpArgs(..) | Terminator::MemoGet(..) | Terminator::MemoGetEager(..) | Terminator::Ret(..) | Terminator::RetCSuspended(..) | Terminator::RetM(..) => false, Terminator::Fatal(..) | Terminator::IterInit(..) | Terminator::IterNext(..) | Terminator::JmpOp { .. } | Terminator::NativeImpl(..) | Terminator::Switch { .. } | Terminator::SSwitch { .. } | Terminator::Throw(..) | Terminator::ThrowAsTypeStructException(..) | Terminator::Unreachable => true, } } } #[derive(Clone, Debug, HasLocals, HasLoc, PartialEq, Eq)] pub struct MemoGet { pub edges: [BlockId; 2], pub locals: Box<[LocalId]>, pub loc: LocId, } impl MemoGet { pub fn new( value_edge: BlockId, no_value_edge: BlockId, locals: &[LocalId], loc: LocId, ) -> Self { MemoGet { edges: [value_edge, no_value_edge], locals: locals.into(), loc, } } pub fn value_edge(&self) -> BlockId { self.edges[0] } pub fn no_value_edge(&self) -> BlockId { self.edges[1] } } impl HasEdges for MemoGet { fn edges(&self) -> &[BlockId] { &self.edges } fn edges_mut(&mut self) -> &mut [BlockId] { &mut self.edges } } #[derive(Clone, Debug, HasLoc, HasLocals, PartialEq, Eq)] pub struct MemoGetEager { pub edges: [BlockId; 3], pub locals: Box<[LocalId]>, pub loc: LocId, } impl MemoGetEager { pub fn new( no_value_edge: BlockId, suspended_edge: BlockId, eager_edge: BlockId, locals: &[LocalId], loc: LocId, ) -> Self { MemoGetEager { edges: [no_value_edge, suspended_edge, eager_edge], locals: locals.into(), loc, } } pub fn no_value_edge(&self) -> BlockId { self.edges[0] } pub fn suspended_edge(&self) -> BlockId { self.edges[1] } pub fn eager_edge(&self) -> BlockId { self.edges[2] } } impl HasEdges for MemoGetEager { fn edges(&self) -> &[BlockId] { &self.edges } fn edges_mut(&mut self) -> &mut [BlockId] { &mut self.edges } } #[derive(Clone, Debug, HasLoc, HasLocals, HasOperands, Display, PartialEq, Eq)] pub enum Hhbc { AKExists([ValueId; 2], LocId), Add([ValueId; 2], LocId), AddElemC([ValueId; 3], LocId), AddNewElemC([ValueId; 2], LocId), ArrayIdx([ValueId; 3], LocId), ArrayMarkLegacy([ValueId; 2], LocId), ArrayUnmarkLegacy([ValueId; 2], LocId), Await(ValueId, LocId), #[has_operands(none)] AwaitAll(Box<[LocalId]>, LocId), #[has_operands(none)] BareThis(BareThisOp, LocId), BitAnd([ValueId; 2], LocId), BitNot(ValueId, LocId), BitOr([ValueId; 2], LocId), BitXor([ValueId; 2], LocId), CGetG(ValueId, LocId), CGetL(LocalId, LocId), CGetQuietL(LocalId, LocId), CGetS([ValueId; 2], ReadonlyOp, LocId), CUGetL(LocalId, LocId), CastBool(ValueId, LocId), CastDict(ValueId, LocId), CastDouble(ValueId, LocId), CastInt(ValueId, LocId), CastKeyset(ValueId, LocId), CastString(ValueId, LocId), CastVec(ValueId, LocId), ChainFaults([ValueId; 2], LocId), CheckClsReifiedGenericMismatch(ValueId, LocId), CheckClsRGSoft(ValueId, LocId), CheckProp(PropId, LocId), CheckThis(LocId), ClassGetC(ValueId, LocId), ClassGetTS(ValueId, LocId), ClassHasReifiedGenerics(ValueId, LocId), ClassName(ValueId, LocId), Clone(ValueId, LocId), ClsCns(ValueId, ConstId, LocId), ClsCnsD(ConstId, ClassId, LocId), ClsCnsL(ValueId, LocalId, LocId), Cmp([ValueId; 2], LocId), CmpOp([ValueId; 2], CmpOp, LocId), ColFromArray(ValueId, CollectionType, LocId), CombineAndResolveTypeStruct(Box<[ValueId]>, LocId), Concat([ValueId; 2], LocId), ConcatN(Box<[ValueId]>, LocId), #[has_operands(none)] ContCheck(ContCheckOp, LocId), ConsumeL(LocalId, LocId), ContCurrent(LocId), ContEnter(ValueId, LocId), ContGetReturn(LocId), ContKey(LocId), ContRaise(ValueId, LocId), ContValid(LocId), CreateCl { operands: Box<[ValueId]>, clsid: ClassId, loc: LocId, }, CreateCont(LocId), CreateSpecialImplicitContext([ValueId; 2], LocId), Div([ValueId; 2], LocId), GetClsRGProp(ValueId, LocId), GetMemoKeyL(LocalId, LocId), HasReifiedParent(ValueId, LocId), Idx([ValueId; 3], LocId), #[has_operands(none)] IncDecL(LocalId, IncDecOp, LocId), IncDecS([ValueId; 2], IncDecOp, LocId), IncludeEval(IncludeEval), InitProp(ValueId, PropId, InitPropOp, LocId), InstanceOfD(ValueId, ClassId, LocId), IsLateBoundCls(ValueId, LocId), IsTypeC(ValueId, IsTypeOp, LocId), #[has_operands(none)] IsTypeL(LocalId, IsTypeOp, LocId), IsTypeStructC([ValueId; 2], TypeStructResolveOp, LocId), IssetG(ValueId, LocId), IssetL(LocalId, LocId), IssetS([ValueId; 2], LocId), #[has_operands(none)] IterFree(IterId, LocId), LateBoundCls(LocId), LazyClass(ClassId, LocId), LazyClassFromClass(ValueId, LocId), LockObj(ValueId, LocId), MemoSet(ValueId, Box<[LocalId]>, LocId), MemoSetEager(ValueId, Box<[LocalId]>, LocId), Modulo([ValueId; 2], LocId), Mul([ValueId; 2], LocId), NewDictArray(/* capacity hint */ u32, LocId), NewKeysetArray(Box<[ValueId]>, LocId), NewObj(ValueId, LocId), NewObjD(ClassId, LocId), #[has_locals(none)] #[has_operands(none)] NewObjS(SpecialClsRef, LocId), NewPair([ValueId; 2], LocId), NewStructDict(Box<[UnitBytesId]>, Box<[ValueId]>, LocId), NewVec(Box<[ValueId]>, LocId), Not(ValueId, LocId), #[has_locals(none)] OODeclExists([ValueId; 2], OODeclExistsOp, LocId), ParentCls(LocId), Pow([ValueId; 2], LocId), Print(ValueId, LocId), RaiseClassStringConversionWarning(LocId), RecordReifiedGeneric(ValueId, LocId), ResolveClass(ClassId, LocId), ResolveClsMethod(ValueId, MethodId, LocId), ResolveClsMethodD(ClassId, MethodId, LocId), #[has_locals(none)] #[has_operands(none)] ResolveClsMethodS(SpecialClsRef, MethodId, LocId), ResolveRClsMethod([ValueId; 2], MethodId, LocId), #[has_locals(none)] ResolveRClsMethodS(ValueId, SpecialClsRef, MethodId, LocId), ResolveFunc(FunctionId, LocId), ResolveRClsMethodD(ValueId, ClassId, MethodId, LocId), ResolveRFunc(ValueId, FunctionId, LocId), ResolveMethCaller(FunctionId, LocId), SelfCls(LocId), SetG([ValueId; 2], LocId), SetImplicitContextByValue(ValueId, LocId), SetL(ValueId, LocalId, LocId), SetOpL(ValueId, LocalId, SetOpOp, LocId), SetOpG([ValueId; 2], SetOpOp, LocId), SetOpS([ValueId; 3], SetOpOp, LocId), SetS([ValueId; 3], ReadonlyOp, LocId), Shl([ValueId; 2], LocId), Shr([ValueId; 2], LocId), #[has_operands(none)] Silence(LocalId, SilenceOp, LocId), Sub([ValueId; 2], LocId), This(LocId), ThrowNonExhaustiveSwitch(LocId), UnsetG(ValueId, LocId), UnsetL(LocalId, LocId), VerifyImplicitContextState(LocId), VerifyOutType(ValueId, LocalId, LocId), VerifyParamType(ValueId, LocalId, LocId), VerifyParamTypeTS(ValueId, LocalId, LocId), VerifyRetTypeC(ValueId, LocId), VerifyRetTypeTS([ValueId; 2], LocId), WHResult(ValueId, LocId), Yield(ValueId, LocId), YieldK([ValueId; 2], LocId), } impl CanThrow for Hhbc { fn can_throw(&self) -> bool { // TODO: Lazy... need to figure out which of these could // actually throw or not. true } } #[derive(Debug, HasLoc, Clone, PartialEq, Eq)] pub enum BaseOp { // Get base from value. Has output of base value. BaseC { mode: MOpMode, loc: LocId, }, // Get base from global name. Mutates global. BaseGC { mode: MOpMode, loc: LocId, }, // Get base from $this. Cannot mutate $this. BaseH { loc: LocId, }, // Get base from local. Mutates local. BaseL { mode: MOpMode, readonly: ReadonlyOp, loc: LocId, }, // Get base from static property. Mutates static property. BaseSC { mode: MOpMode, readonly: ReadonlyOp, loc: LocId, }, // Not allowed in HHBC - Get base from static property. BaseST { mode: MOpMode, readonly: ReadonlyOp, loc: LocId, prop: PropId, }, } #[derive(Debug, HasLoc, Clone, PartialEq, Eq)] pub struct IntermediateOp { pub key: MemberKey, pub mode: MOpMode, pub readonly: ReadonlyOp, pub loc: LocId, } #[derive(Debug, HasLoc, Clone, PartialEq, Eq)] pub enum FinalOp { IncDecM { key: MemberKey, readonly: ReadonlyOp, inc_dec_op: IncDecOp, loc: LocId, }, QueryM { key: MemberKey, readonly: ReadonlyOp, query_m_op: QueryMOp, loc: LocId, }, SetM { key: MemberKey, readonly: ReadonlyOp, loc: LocId, }, SetRangeM { sz: u32, set_range_op: SetRangeOp, loc: LocId, }, SetOpM { key: MemberKey, readonly: ReadonlyOp, set_op_op: SetOpOp, loc: LocId, }, UnsetM { key: MemberKey, readonly: ReadonlyOp, loc: LocId, }, } impl FinalOp { pub fn key(&self) -> Option<&MemberKey> { match self { FinalOp::IncDecM { key, .. } | FinalOp::QueryM { key, .. } | FinalOp::SetM { key, .. } | FinalOp::SetOpM { key, .. } | FinalOp::UnsetM { key, .. } => Some(key), FinalOp::SetRangeM { .. } => None, } } pub fn is_write(&self) -> bool { match self { FinalOp::QueryM { .. } => false, FinalOp::IncDecM { .. } | FinalOp::SetM { .. } | FinalOp::SetOpM { .. } | FinalOp::UnsetM { .. } | FinalOp::SetRangeM { .. } => true, } } } #[derive(Debug, HasLoc, HasLocals, HasOperands, Clone, PartialEq, Eq)] #[has_loc("base_op")] pub struct MemberOp { pub operands: Box<[ValueId]>, pub locals: Box<[LocalId]>, pub base_op: BaseOp, pub intermediate_ops: Box<[IntermediateOp]>, pub final_op: FinalOp, } impl MemberOp { /// Return the number of values this MemberOp produces. This should match /// the number of `Select` Instrs that follow this Instr. pub fn num_values(&self) -> usize { let (rets_from_final, write_op) = match self.final_op { FinalOp::SetRangeM { .. } => (0, true), FinalOp::UnsetM { .. } => (0, true), FinalOp::IncDecM { .. } => (1, true), FinalOp::QueryM { .. } => (1, false), FinalOp::SetM { .. } => (1, true), FinalOp::SetOpM { .. } => (1, true), }; let base_key_is_element_access = self.intermediate_ops.get(0).map_or_else( || self.final_op.key().map_or(true, |k| k.is_element_access()), |dim| dim.key.is_element_access(), ); let rets_from_base = match self.base_op { BaseOp::BaseC { .. } => (base_key_is_element_access && write_op) as usize, BaseOp::BaseGC { .. } | BaseOp::BaseH { .. } | BaseOp::BaseL { .. } | BaseOp::BaseSC { .. } | BaseOp::BaseST { .. } => 0, }; rets_from_base + rets_from_final } } impl CanThrow for MemberOp { fn can_throw(&self) -> bool { // TODO: Lazy... need to figure out which of these could actually throw // or not. true } } #[derive(Clone, Debug, PartialEq, Eq)] pub enum CallDetail { // A::$b(42); // $a::$b(42); FCallClsMethod { log: IsLogAsDynamicCallOp, }, // A::foo(42); FCallClsMethodD { clsid: ClassId, method: MethodId, }, // $a::foo(42); FCallClsMethodM { method: MethodId, log: IsLogAsDynamicCallOp, }, // self::$a(); FCallClsMethodS { clsref: SpecialClsRef, }, // self::foo(); FCallClsMethodSD { clsref: SpecialClsRef, method: MethodId, }, // new A(42); FCallCtor, // $a(42); FCallFunc, // foo(42); FCallFuncD { func: FunctionId, }, // $a->$b(42); FCallObjMethod { flavor: ObjMethodOp, }, // $a->foo(42); FCallObjMethodD { flavor: ObjMethodOp, method: MethodId, }, } impl CallDetail { pub fn args<'a>(&self, operands: &'a [ValueId]) -> &'a [ValueId] { let len = operands.len(); match self { CallDetail::FCallClsMethod { .. } => &operands[..len - 2], CallDetail::FCallFunc => &operands[..len - 1], CallDetail::FCallObjMethod { .. } => &operands[1..len - 1], CallDetail::FCallClsMethodM { .. } => &operands[..len - 1], CallDetail::FCallClsMethodS { .. } => &operands[..len - 1], CallDetail::FCallClsMethodD { .. } => operands, CallDetail::FCallClsMethodSD { .. } => operands, CallDetail::FCallCtor => &operands[1..], CallDetail::FCallFuncD { .. } => operands, CallDetail::FCallObjMethodD { .. } => &operands[1..], } } pub fn class(&self, operands: &[ValueId]) -> ValueId { let len = operands.len(); match self { CallDetail::FCallClsMethod { .. } | CallDetail::FCallClsMethodM { .. } => { operands[len - 1] } CallDetail::FCallClsMethodD { .. } | CallDetail::FCallClsMethodS { .. } | CallDetail::FCallClsMethodSD { .. } | CallDetail::FCallCtor | CallDetail::FCallFunc | CallDetail::FCallFuncD { .. } | CallDetail::FCallObjMethod { .. } | CallDetail::FCallObjMethodD { .. } => { panic!("Cannot call 'class' on detail of type {:?}", self) } } } pub fn method(&self, operands: &[ValueId]) -> ValueId { let len = operands.len(); match self { CallDetail::FCallClsMethod { .. } => operands[len - 2], CallDetail::FCallClsMethodS { .. } | CallDetail::FCallObjMethod { .. } => { operands[len - 1] } CallDetail::FCallClsMethodD { .. } | CallDetail::FCallClsMethodM { .. } | CallDetail::FCallClsMethodSD { .. } | CallDetail::FCallCtor | CallDetail::FCallFunc | CallDetail::FCallFuncD { .. } | CallDetail::FCallObjMethodD { .. } => { panic!("Cannot call 'method' on detail of type {:?}", self) } } } pub fn obj(&self, operands: &[ValueId]) -> ValueId { match self { CallDetail::FCallCtor | CallDetail::FCallObjMethodD { .. } | CallDetail::FCallObjMethod { .. } => operands[0], CallDetail::FCallClsMethod { .. } | CallDetail::FCallClsMethodD { .. } | CallDetail::FCallClsMethodM { .. } | CallDetail::FCallClsMethodS { .. } | CallDetail::FCallClsMethodSD { .. } | CallDetail::FCallFunc | CallDetail::FCallFuncD { .. } => { panic!("Cannot call 'obj' on detail of type {:?}", self) } } } pub fn target(&self, operands: &[ValueId]) -> ValueId { let len = operands.len(); match self { CallDetail::FCallFunc => operands[len - 1], CallDetail::FCallCtor | CallDetail::FCallObjMethodD { .. } | CallDetail::FCallClsMethodD { .. } | CallDetail::FCallClsMethodM { .. } | CallDetail::FCallClsMethodS { .. } | CallDetail::FCallClsMethod { .. } | CallDetail::FCallObjMethod { .. } | CallDetail::FCallClsMethodSD { .. } | CallDetail::FCallFuncD { .. } => { panic!("Cannot call 'target' on detail of type {:?}", self) } } } } #[derive(Clone, Debug, HasLoc, HasLocals, HasOperands, PartialEq, Eq)] #[has_locals(none)] pub struct Call { pub operands: Box<[ValueId]>, pub context: UnitBytesId, pub detail: CallDetail, pub flags: FCallArgsFlags, pub num_rets: u32, /// For calls with inout parameters this is a sorted list of the indices /// of those parameters. pub inouts: Option<Box<[u32]>>, /// For calls with readonly parameters this is a sorted list of the indices /// of those parameters. pub readonly: Option<Box<[u32]>>, pub loc: LocId, } impl Call { pub fn args(&self) -> &[ValueId] { self.detail.args(&self.operands) } pub fn obj(&self) -> ValueId { self.detail.obj(&self.operands) } pub fn target(&self) -> ValueId { self.detail.target(&self.operands) } } impl CanThrow for Call { fn can_throw(&self) -> bool { // TODO: Lazy... need to figure out which of these could actually throw // or not. true } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum IncludeKind { Eval, Include, IncludeOnce, Require, RequireOnce, RequireOnceDoc, } #[derive(Clone, Debug, HasLoc, HasLocals, HasOperands, PartialEq, Eq)] #[has_locals(none)] pub struct IncludeEval { pub kind: IncludeKind, pub vid: ValueId, pub loc: LocId, } impl CanThrow for IncludeEval { fn can_throw(&self) -> bool { // TODO: Lazy... need to figure out which of these could actually throw // or not. true } } #[derive(Debug, Clone, PartialEq, Eq)] pub enum MemberKey { // cell from stack as index // $a[foo()] EC, // immediate // $a[3] EI(i64), // local (stored in locals array on MemberOp) as index // $a[$b] EL, // literal string as index // $a["hello"] ET(UnitBytesId), // cell from stack as property // $a->(foo()) PC, // local (stored in locals array on MemberOp) as property // $a->($b) PL, // literal string as property // $a->hello PT(PropId), // nullsafe PT // $a?->hello QT(PropId), // new element // $a[] W, } impl MemberKey { pub fn is_element_access(&self) -> bool { match self { MemberKey::EC | MemberKey::EI(_) | MemberKey::EL | MemberKey::ET(_) | MemberKey::W => { true } MemberKey::PC | MemberKey::PL | MemberKey::PT(_) | MemberKey::QT(_) => false, } } } // The ValueId param is laid out so that we can chop off the optional args and // always be able to produce a valid operands slice: // [optional: key_vid, required: base, optional: value] // // For accessors to this fixed-size data it's strongly recommended that it is ok // to match [x, y, _] but never ok to refer to elems by number [1] -- for the // latter case always use an accessor. #[derive(Debug, HasLoc)] pub struct MemberArgs([ValueId; 3], pub MemberKey, pub LocId); impl MemberArgs { pub fn new( base: ValueId, (key, key_vid): (MemberKey, Option<ValueId>), value: Option<ValueId>, loc: LocId, ) -> Self { let key_vid = key_vid.unwrap_or_else(ValueId::none); let value = value.unwrap_or_else(ValueId::none); Self([key_vid, base, value], key, loc) } pub fn base(&self) -> ValueId { let Self([_, base, _], _, _) = *self; base } pub fn key(&self) -> &MemberKey { let Self(_, key, _) = self; key } pub fn key_vid(&self) -> Option<ValueId> { let Self([vid, _, _], _, _) = *self; if vid.is_none() { None } else { Some(vid) } } pub fn value(&self) -> Option<ValueId> { let Self([_, _, value], _, _) = *self; if value.is_none() { None } else { Some(value) } } } impl HasOperands for MemberArgs { fn operands(&self) -> &[ValueId] { let Self(ops, _, _) = self; let a = ops[0].is_none() as usize; let b = !ops[2].is_none() as usize + 2; &ops[a..b] } fn operands_mut(&mut self) -> &mut [ValueId] { let Self(ops, _, _) = self; let a = ops[0].is_none() as usize; let b = !ops[2].is_none() as usize + 2; &mut ops[a..b] } } impl CanThrow for MemberArgs { fn can_throw(&self) -> bool { // TODO: Lazy... need to figure out which of these could actually throw // or not. true } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Predicate { NonZero, Zero, } #[derive(Clone, Debug, HasLoc, PartialEq, Eq)] pub struct IteratorArgs { pub iter_id: IterId, // Stored as [ValueLid, KeyLid] pub locals: SmallVec<[LocalId; 2]>, pub targets: [BlockId; 2], pub loc: LocId, } impl IteratorArgs { pub fn new( iter_id: IterId, key_lid: Option<LocalId>, value_lid: LocalId, done_bid: BlockId, next_bid: BlockId, loc: LocId, ) -> Self { let mut locals = SmallVec::new(); locals.push(value_lid); if let Some(key_lid) = key_lid { locals.push(key_lid); } IteratorArgs { iter_id, locals, targets: [done_bid, next_bid], loc, } } pub fn key_lid(&self) -> Option<LocalId> { self.locals.get(1).copied() } pub fn value_lid(&self) -> LocalId { self.locals[0] } pub fn done_bid(&self) -> BlockId { self.targets[0] } pub fn next_bid(&self) -> BlockId { self.targets[1] } } impl HasLocals for IteratorArgs { fn locals(&self) -> &[LocalId] { self.locals.as_slice() } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum CmpOp { Eq, Gt, Gte, Lt, Lte, NSame, Neq, Same, } /// Instructions used by the SSA pass. #[derive(Clone, Debug, HasLoc, HasLocals, HasOperands, PartialEq, Eq)] pub enum Tmp { SetVar(VarId, ValueId), // var, value GetVar(VarId), // var } /// Instructions used during ir_to_bc. #[derive(Clone, Debug, HasLoc, HasLocals, HasOperands, PartialEq, Eq)] pub enum IrToBc { PopC, PopL(LocalId), PushL(LocalId), PushConstant(ValueId), PushUninit, UnsetL(LocalId), } /// Instructions used during conversions/textual. #[derive(Clone, Debug, HasLoc, HasLocals, HasOperands, PartialEq, Eq)] pub enum Textual { /// If the expression is not true then halt execution along this path. /// (this is what Textual calls 'prune') #[has_locals(none)] AssertTrue(ValueId, LocId), /// If the expression is true then halt execution along this path. /// (this is what Textual calls 'prune not') #[has_locals(none)] AssertFalse(ValueId, LocId), /// Special Deref marker for a variable. #[has_operands(none)] #[has_loc(none)] Deref(LocalId), /// Special call to a Hack builtin function (like `hack_string`) skipping /// the normal Hack function ABI. #[has_locals(none)] HackBuiltin { target: Cow<'static, str>, values: Box<[ValueId]>, loc: LocId, }, #[has_operands(none)] #[has_loc(none)] #[has_locals(none)] LoadGlobal { id: GlobalId, is_const: bool }, /// Literal String #[has_operands(none)] #[has_loc(none)] #[has_locals(none)] String(UnitBytesId), } impl Textual { pub fn deref(lid: LocalId) -> Instr { Instr::Special(Special::Textual(Textual::Deref(lid))) } } #[derive(Clone, Debug, HasLoc, HasLocals, HasOperands, PartialEq, Eq)] pub enum Special { Copy(ValueId), IrToBc(IrToBc), Param, Select(ValueId, u32), Textual(Textual), // Used to build SSA. #[has_locals(none)] #[has_loc(none)] Tmp(Tmp), Tombstone, } impl CanThrow for Special { fn can_throw(&self) -> bool { // TODO: Lazy... need to figure out which of these could actually throw // or not. true } } impl Instr { pub fn call(call: Call) -> Instr { Instr::Call(Box::new(call)) } pub fn simple_call(func: FunctionId, operands: &[ValueId], loc: LocId) -> Instr { Self::call(Call { operands: operands.into(), context: UnitBytesId::NONE, detail: CallDetail::FCallFuncD { func }, flags: FCallArgsFlags::default(), num_rets: 0, inouts: None, readonly: None, loc, }) } pub fn simple_method_call( method: MethodId, receiver: ValueId, operands: &[ValueId], loc: LocId, ) -> Instr { Self::call(Call { operands: std::iter::once(receiver) .chain(operands.iter().copied()) .collect(), context: UnitBytesId::NONE, detail: CallDetail::FCallObjMethodD { flavor: ObjMethodOp::NullThrows, method, }, flags: FCallArgsFlags::default(), num_rets: 0, inouts: None, readonly: None, loc, }) } pub fn method_call_special( clsref: SpecialClsRef, method: MethodId, operands: &[ValueId], loc: LocId, ) -> Instr { Self::call(Call { operands: operands.into(), context: UnitBytesId::NONE, detail: CallDetail::FCallClsMethodSD { clsref, method }, flags: FCallArgsFlags::default(), num_rets: 0, inouts: None, readonly: None, loc, }) } pub fn jmp(bid: BlockId, loc: LocId) -> Instr { Instr::Terminator(Terminator::Jmp(bid, loc)) } pub fn enter(bid: BlockId, loc: LocId) -> Instr { Instr::Terminator(Terminator::Enter(bid, loc)) } pub fn jmp_args(bid: BlockId, args: &[ValueId], loc: LocId) -> Instr { let args = args.to_vec().into_boxed_slice(); Instr::Terminator(Terminator::JmpArgs(bid, args, loc)) } pub fn jmp_op( cond: ValueId, pred: Predicate, true_bid: BlockId, false_bid: BlockId, loc: LocId, ) -> Instr { Instr::Terminator(Terminator::JmpOp { cond, pred, targets: [true_bid, false_bid], loc, }) } pub fn param() -> Instr { Instr::Special(Special::Param) } pub fn ret(vid: ValueId, loc: LocId) -> Instr { Instr::Terminator(Terminator::Ret(vid, loc)) } pub fn tombstone() -> Instr { Instr::Special(Special::Tombstone) } pub fn copy(value: ValueId) -> Instr { Instr::Special(Special::Copy(value)) } pub fn unreachable() -> Instr { Instr::Terminator(Terminator::Unreachable) } pub fn set_var(var: VarId, value: ValueId) -> Instr { Instr::Special(Special::Tmp(Tmp::SetVar(var, value))) } pub fn get_var(var: VarId) -> Instr { Instr::Special(Special::Tmp(Tmp::GetVar(var))) } } newtype_int!(UnnamedLocalId, u32, UnnamedLocalIdMap, UnnamedLocalIdSet); /// Note: Unlike HHBC the IR named and unnamed are in distinct namespaces. #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)] pub enum LocalId { Named(UnitBytesId), // The UnnamedLocalIds are just for uniqueness - there are no requirements // for these IDs to be contiguous or in any particular order. Unnamed(UnnamedLocalId), } #[test] fn check_sizes() { use static_assertions::assert_eq_size; assert_eq_size!(ValueId, u32); }
Rust
hhvm/hphp/hack/src/hackc/ir/ir_core/lib.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. #![feature(const_option)] //! # The HackC IR //! //! This is an IR representation of the Hack code. //! //! A Hack program is organized into "units". Each `Unit` (see `Unit` in //! unit.rs) represents a single Hack source file - although there is no reason //! multiple units couldn't be merged together to form a larger unit. //! //! Units are composed of the information needed to represent the program: //! classes, constants, functions, typedefs. //! //! Each class (see `Class` in class.rs) has a class description and a list of //! methods. //! //! Methods (see `Method` in func.rs) and functions (see `Function` in func.rs) //! are backed by a common `Func` structure (see `Func` in func.rs) which is the //! basic representation of a Hack callable. //! //! Funcs are composed of instructions (see `Instr` in instr.rs) and basic //! blocks (see `Block` in block.rs). //! pub mod block; pub mod class; pub mod coeffects; pub mod common; pub mod constant; pub mod func; pub mod func_builder; pub mod func_builder_ex; pub mod instr; pub mod module; pub mod newtype; pub mod string_intern; pub mod type_const; pub mod type_struct; pub mod typed_value; pub mod types; pub mod unit; // Re-export some types in from hhbc so users of `ir` don't have to figure out // which random stuff to get from `ir` and which to get elsewhere. pub use hhbc::BareThisOp; pub use hhbc::CcParam; pub use hhbc::ClassName; pub use hhbc::ClassishKind; pub use hhbc::CollectionType; pub use hhbc::ConstName; pub use hhbc::ContCheckOp; pub use hhbc::FCallArgsFlags; pub use hhbc::FatalOp; pub use hhbc::FloatBits; pub use hhbc::FunctionFlags; pub use hhbc::FunctionName; pub use hhbc::IncDecOp; pub use hhbc::IncludePath; pub use hhbc::InitPropOp; pub use hhbc::IsLogAsDynamicCallOp; pub use hhbc::IsTypeOp; pub use hhbc::IterId; pub use hhbc::MOpMode; pub use hhbc::MethodFlags; pub use hhbc::MethodName; pub use hhbc::OODeclExistsOp; pub use hhbc::ObjMethodOp; pub use hhbc::QueryMOp; pub use hhbc::ReadonlyOp; pub use hhbc::SetOpOp; pub use hhbc::SetRangeOp; pub use hhbc::SilenceOp; pub use hhbc::Span; pub use hhbc::SpecialClsRef; pub use hhbc::SwitchKind; pub use hhbc::TraitReqKind; pub use hhbc::TypeStructResolveOp; pub use hhbc::Visibility; pub use hhvm_types_ffi::ffi::Attr; pub use hhvm_types_ffi::ffi::TypeConstraintFlags; pub use hhvm_types_ffi::ffi::TypeStructureKind; pub use naming_special_names_rust::coeffects::Ctx; pub use self::block::Block; pub use self::class::Class; pub use self::class::Property; pub use self::coeffects::CcReified; pub use self::coeffects::CcThis; pub use self::coeffects::Coeffects; pub use self::coeffects::CtxConstant; pub use self::common::Attribute; pub use self::constant::Constant; pub use self::constant::HackConstant; pub use self::func::ExFrameId; pub use self::func::Filename; pub use self::func::Func; pub use self::func::Function; pub use self::func::Method; pub use self::func::Param; pub use self::func::SrcLoc; pub use self::func::TParamBounds; pub use self::func::TryCatchId; pub use self::func_builder::FuncBuilder; pub use self::func_builder::MemberOpBuilder; pub use self::func_builder_ex::FuncBuilderEx; pub use self::instr::Call; pub use self::instr::HasEdges; pub use self::instr::Instr; pub use self::instr::LocalId; pub use self::instr::Predicate; pub use self::instr::UnnamedLocalId; pub use self::module::Module; pub use self::newtype::BlockId; pub use self::newtype::BlockIdMap; pub use self::newtype::BlockIdSet; pub use self::newtype::ClassId; pub use self::newtype::ClassIdMap; pub use self::newtype::ConstId; pub use self::newtype::ConstantId; pub use self::newtype::FullInstrId; pub use self::newtype::FunctionId; pub use self::newtype::GlobalId; pub use self::newtype::InstrId; pub use self::newtype::InstrIdMap; pub use self::newtype::InstrIdSet; pub use self::newtype::LocId; pub use self::newtype::MethodId; pub use self::newtype::PropId; pub use self::newtype::ValueId; pub use self::newtype::ValueIdMap; pub use self::newtype::ValueIdSet; pub use self::newtype::VarId; pub use self::string_intern::StringInterner; pub use self::string_intern::UnitBytesId; pub use self::type_const::TypeConstant; pub use self::typed_value::ArrayKey; pub use self::typed_value::DictValue; pub use self::typed_value::KeysetValue; pub use self::typed_value::TypedValue; pub use self::types::BaseType; pub use self::types::EnforceableType; pub use self::types::TypeInfo; pub use self::types::Typedef; pub use self::unit::Fatal; pub use self::unit::Unit;
Rust
hhvm/hphp/hack/src/hackc/ir/ir_core/module.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use ffi::Str; use crate::func::SrcLoc; use crate::Attribute; use crate::ClassId; #[derive(Debug)] pub struct Module<'a> { pub attributes: Vec<Attribute>, pub name: ClassId, pub src_loc: SrcLoc, pub doc_comment: Option<Str<'a>>, }
Rust
hhvm/hphp/hack/src/hackc/ir/ir_core/newtype.rs
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. // Re-export some types in from hhbc so users of `ir` don't have to figure out // which random stuff to get from `ir` and which to get elsewhere. use bstr::BStr; use naming_special_names_rust::members; use newtype::newtype_int; use parking_lot::MappedRwLockReadGuard; use crate::string_intern::StringInterner; use crate::UnitBytesId; macro_rules! interned_hhbc_id { ($name: ident, $hhbc: ident) => { #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub struct $name { pub id: UnitBytesId, } impl $name { pub fn new(id: UnitBytesId) -> Self { Self { id } } pub fn from_hhbc<'a>(id: hhbc::$hhbc<'a>, strings: &StringInterner) -> Self { Self::new(strings.intern_bytes(id.as_bytes())) } pub fn from_str(name: &str, strings: &StringInterner) -> Self { Self::new(strings.intern_str(name)) } pub fn from_bytes(name: &[u8], strings: &StringInterner) -> Self { Self::new(strings.intern_bytes(name)) } pub fn as_bytes<'a>( self, strings: &'a StringInterner, ) -> MappedRwLockReadGuard<'a, [u8]> { strings.lookup_bytes(self.id) } pub fn as_bstr<'a>( self, strings: &'a StringInterner, ) -> MappedRwLockReadGuard<'a, BStr> { strings.lookup_bstr(self.id) } } }; } interned_hhbc_id!(ClassId, ClassName); pub type ClassIdMap<T> = indexmap::map::IndexMap<ClassId, T, newtype::BuildIdHasher<u32>>; interned_hhbc_id!(ConstId, ConstName); interned_hhbc_id!(FunctionId, FunctionName); const __FACTORY: &str = "__factory"; pub const _86CINIT: &str = "86cinit"; pub const _86PINIT: &str = "86pinit"; pub const _86SINIT: &str = "86sinit"; interned_hhbc_id!(MethodId, MethodName); impl MethodId { pub fn _86cinit(strings: &StringInterner) -> Self { Self::from_str(_86CINIT, strings) } pub fn _86pinit(strings: &StringInterner) -> Self { Self::from_str(_86PINIT, strings) } pub fn _86sinit(strings: &StringInterner) -> Self { Self::from_str(_86SINIT, strings) } pub fn constructor(strings: &StringInterner) -> Self { Self::from_str(members::__CONSTRUCT, strings) } pub fn factory(strings: &StringInterner) -> Self { Self::from_str(__FACTORY, strings) } pub fn is_86cinit(&self, strings: &StringInterner) -> bool { strings.eq_str(self.id, _86CINIT) } pub fn is_86pinit(&self, strings: &StringInterner) -> bool { strings.eq_str(self.id, _86PINIT) } pub fn is_86sinit(&self, strings: &StringInterner) -> bool { strings.eq_str(self.id, _86SINIT) } pub fn is_constructor(&self, strings: &StringInterner) -> bool { strings.eq_str(self.id, members::__CONSTRUCT) } } interned_hhbc_id!(PropId, PropName); // A BlockId represents a Block within a Func. newtype_int!(BlockId, u32, BlockIdMap, BlockIdSet); // A InstrId represents a Instr within a Func. newtype_int!(InstrId, u32, InstrIdMap, InstrIdSet); pub type InstrIdIndexSet = indexmap::set::IndexSet<InstrId, newtype::BuildIdHasher<u32>>; // A ConstantId represents a Constant within a Func. newtype_int!(ConstantId, u32, ConstantIdMap, ConstantIdSet); // A LocId represents a SrcLoc interned within a Func. newtype_int!(LocId, u32, LocIdMap, LocIdSet); // A VarId represents an internal variable which is removed by the ssa pass. // They are disjoint from LocalIds. newtype_int!(VarId, u32, VarIdMap, VarIdSet); /// An ValueId can be either an InstrId or a ConstantId. /// /// Note that special care has been taken to make sure this encodes to the same /// size as a u32: /// InstrId values are encoded as non-negative values. /// ConstantId values are encoded as binary negation (so negative values). /// None is encoded as i32::MIN_INT. #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] pub struct ValueId { raw: i32, } impl ValueId { const NONE: i32 = i32::MIN; pub fn raw(self) -> i32 { self.raw } pub fn from_instr(idx: InstrId) -> Self { assert!(idx != InstrId::NONE); let InstrId(idx) = idx; Self { raw: idx as i32 } } pub fn from_constant(idx: ConstantId) -> Self { assert!(idx != ConstantId::NONE); let ConstantId(idx) = idx; Self { raw: !(idx as i32) } } pub fn none() -> Self { Self { raw: Self::NONE } } pub fn expect_instr(self, msg: &str) -> InstrId { if self.raw >= 0 { InstrId(self.raw as u32) } else { panic!("{}", msg); } } pub fn full(self) -> FullInstrId { if self.raw >= 0 { FullInstrId::Instr(InstrId(self.raw as u32)) } else if self.raw == Self::NONE { FullInstrId::None } else { FullInstrId::Constant(ConstantId((!self.raw) as u32)) } } pub fn constant(self) -> Option<ConstantId> { if self.raw >= 0 || self.raw == Self::NONE { None } else { Some(ConstantId((!self.raw) as u32)) } } pub fn instr(self) -> Option<InstrId> { if self.raw >= 0 { Some(InstrId(self.raw as u32)) } else { None } } pub fn is_constant(self) -> bool { self.raw < 0 && self.raw != Self::NONE } pub fn is_instr(self) -> bool { self.raw >= 0 } pub fn is_none(self) -> bool { self.raw == Self::NONE } } impl From<InstrId> for ValueId { fn from(iid: InstrId) -> ValueId { Self::from_instr(iid) } } impl From<ConstantId> for ValueId { fn from(cid: ConstantId) -> ValueId { Self::from_constant(cid) } } // A 'FullInstrId' can be used with match but takes more memory than // ValueId. Note that the Constant and Instr variants will never contain // ConstantId::NONE or InstrId::NONE. pub enum FullInstrId { Instr(InstrId), Constant(ConstantId), None, } pub type ValueIdMap<V> = std::collections::HashMap<ValueId, V, newtype::BuildIdHasher<u32>>; pub type ValueIdSet = std::collections::HashSet<ValueId, newtype::BuildIdHasher<u32>>; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct GlobalId { pub id: UnitBytesId, } impl GlobalId { pub fn new(id: UnitBytesId) -> Self { Self { id } } pub fn as_bytes<'a>(self, strings: &'a StringInterner) -> MappedRwLockReadGuard<'a, [u8]> { strings.lookup_bytes(self.id) } }
Rust
hhvm/hphp/hack/src/hackc/ir/ir_core/string_intern.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::borrow::Cow; use bstr::BStr; use hash::IndexSet; use newtype::newtype_int; use parking_lot::MappedRwLockReadGuard; use parking_lot::RwLock; use parking_lot::RwLockReadGuard; // Improvement list: // // - In debug mode have UnitBytesId store a pointer to the original // StringInterner and check that whenever the UnitBytesId is used to look up // values in the table. It's not as safe as using lifetimes to track it but it's // a lot cleaner code. // A UnitBytesId represents an entry in the Unit::strings table. newtype_int!(UnitBytesId, u32, UnitBytesIdMap, UnitBytesIdSet); impl UnitBytesId { pub fn display<'a>(self, strings: &'a StringInterner) -> impl std::fmt::Display + 'a { struct D<'a>(UnitBytesId, &'a StringInterner); impl std::fmt::Display for D<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.1.lookup_bstr(self.0).fmt(f) } } D(self, strings) } pub fn is_empty(self, strings: &StringInterner) -> bool { strings.eq_str(self, "") } } /// A string interner for associating IDs with unique string values. If two /// identical strings are inserted into the StringInterner they are guaranteed /// to have the same UnitBytesId. /// /// Note that there are no guarantees about the numerical values or ordering of /// the resulting UnitBytesId - in particular use of StringInterner in /// multi-thread situations will produce non-deterministic ID ordering. /// /// Currently there is no easy facility to iterate the strings in-order - this /// prevents accidental ordering misuse. #[derive(Default)] pub struct StringInterner { values: RwLock<IndexSet<Vec<u8>>>, read_only: bool, } impl StringInterner { pub fn read_only() -> StringInterner { StringInterner { values: Default::default(), read_only: true, } } pub fn intern_bytes<'b>(&self, s: impl Into<Cow<'b, [u8]>>) -> UnitBytesId { let s = s.into(); // We could use an upgradable_read() - but there's only one of those // allowed at a time so we'd lose read concurrency. let values = self.values.read(); if let Some(index) = values.get_index_of(s.as_ref()) { return UnitBytesId::from_usize(index); } drop(values); assert!(!self.read_only); let mut values = self.values.write(); UnitBytesId::from_usize(if let Some(index) = values.get_index_of(s.as_ref()) { index } else { values.insert_full(s.into_owned()).0 }) } // TODO: This should return UnitStringId pub fn intern_str<'b>(&self, s: impl Into<Cow<'b, str>>) -> UnitBytesId { let s = s.into(); match s { Cow::Owned(s) => self.intern_bytes(s.into_bytes()), Cow::Borrowed(s) => self.intern_bytes(s.as_bytes()), } } pub fn is_empty(&self) -> bool { self.values.read().is_empty() } pub fn len(&self) -> usize { self.values.read().len() } pub fn lookup_bytes<'a>(&'a self, id: UnitBytesId) -> MappedRwLockReadGuard<'a, [u8]> { assert!(id != UnitBytesId::NONE); let values = self.values.read(); RwLockReadGuard::map(values, |values| -> &[u8] { &values[id.as_usize()] }) } pub fn lookup_bytes_or_none<'a>( &'a self, id: UnitBytesId, ) -> Option<MappedRwLockReadGuard<'a, [u8]>> { if id == UnitBytesId::NONE { None } else { Some(self.lookup_bytes(id)) } } pub fn lookup_bstr<'a>(&'a self, id: UnitBytesId) -> MappedRwLockReadGuard<'a, BStr> { MappedRwLockReadGuard::map(self.lookup_bytes(id), |v: &[u8]| -> &BStr { v.into() }) } pub fn eq_str(&self, id: UnitBytesId, rhs: &str) -> bool { let lhs = self.lookup_bytes(id); lhs.as_ref() as &[u8] == rhs.as_bytes() } /// This is meant for debugging ONLY. pub fn debug_for_each<F>(&self, mut f: F) where F: FnMut(UnitBytesId, &[u8]), { self.values .read() .iter() .enumerate() .for_each(|(idx, s)| f(UnitBytesId::from_usize(idx), s)) } } impl std::fmt::Debug for StringInterner { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("{intern}") } }
Rust
hhvm/hphp/hack/src/hackc/ir/ir_core/typed_value.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::sync::Arc; use hash::IndexMap; use hash::IndexSet; use crate::ClassId; use crate::Constant; use crate::FloatBits; use crate::TypeInfo; use crate::UnitBytesId; #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub enum TypedValue { Bool(bool), Dict(DictValue), Float(FloatBits), Int(i64), Keyset(KeysetValue), LazyClass(ClassId), Null, String(UnitBytesId), Uninit, Vec(Vec<TypedValue>), } impl TypedValue { pub fn type_info(&self) -> TypeInfo { use crate::types::BaseType; match self { TypedValue::Bool(_) => BaseType::Bool.into(), TypedValue::Dict(_) => BaseType::Dict.into(), TypedValue::Float(_) => BaseType::Float.into(), TypedValue::Int(_) => BaseType::Int.into(), TypedValue::Keyset(_) => BaseType::Keyset.into(), TypedValue::LazyClass(_) => BaseType::String.into(), TypedValue::Null => BaseType::Null.into(), TypedValue::String(_) => BaseType::String.into(), TypedValue::Uninit => TypeInfo::empty(), TypedValue::Vec(_) => BaseType::Vec.into(), } } pub fn get_dict(&self) -> Option<&DictValue> { match self { TypedValue::Dict(dv) => Some(dv), _ => None, } } pub fn get_int(&self) -> Option<i64> { match self { TypedValue::Int(num) => Some(*num), _ => None, } } pub fn get_string(&self) -> Option<UnitBytesId> { match self { TypedValue::String(str) => Some(*str), _ => None, } } } impl<'a> From<TypedValue> for Constant<'a> { fn from(tv: TypedValue) -> Self { match tv { TypedValue::Bool(b) => Constant::Bool(b), TypedValue::Float(f) => Constant::Float(f), TypedValue::Int(i) => Constant::Int(i), TypedValue::LazyClass(id) => Constant::String(id.id), TypedValue::Null => Constant::Null, TypedValue::String(id) => Constant::String(id), TypedValue::Uninit => Constant::Uninit, TypedValue::Dict(_) | TypedValue::Keyset(_) | TypedValue::Vec(_) => { Constant::Array(Arc::new(tv)) } } } } #[derive(Clone, Debug, Eq, PartialEq, Hash)] pub enum ArrayKey { Int(i64), String(UnitBytesId), LazyClass(ClassId), } /// A wrapper around IndexSet<ArrayKey> which includes key ordering for /// comparisons and provides hash. #[derive(Clone, Debug, Default)] pub struct KeysetValue(pub IndexSet<ArrayKey>); impl std::ops::Deref for KeysetValue { type Target = IndexSet<ArrayKey>; fn deref(&self) -> &IndexSet<ArrayKey> { &self.0 } } impl std::cmp::PartialEq for KeysetValue { fn eq(&self, other: &KeysetValue) -> bool { // IndexSet implements PartialEq but it ignores insertion order, // which we care about. self.len() == other.len() && self.iter().zip(other.iter()).all(|(a, b)| a == b) } } impl std::cmp::Eq for KeysetValue {} impl std::hash::Hash for KeysetValue { fn hash<H: std::hash::Hasher>(&self, h: &mut H) { // IndexSet doesn't implement Hash so we need to provide our // own. It needs to match TypedValue::eq() which uses insertion // ordering so we'll do the same. for v in self.iter() { v.hash(h); } } } impl FromIterator<ArrayKey> for KeysetValue { fn from_iter<T>(iterator: T) -> Self where T: IntoIterator<Item = ArrayKey>, { Self(IndexSet::from_iter(iterator)) } } /// A wrapper around IndexMap<ArrayKey, TypedValue> which includes key ordering /// for comparisons and provides hash. #[derive(Clone, Debug, Default)] pub struct DictValue(pub IndexMap<ArrayKey, TypedValue>); impl std::ops::Deref for DictValue { type Target = IndexMap<ArrayKey, TypedValue>; fn deref(&self) -> &IndexMap<ArrayKey, TypedValue> { &self.0 } } impl std::cmp::PartialEq for DictValue { fn eq(&self, other: &DictValue) -> bool { // IndexMap implements PartialEq but it ignores insertion order, // which we care about. self.len() == other.len() && self.iter().zip(other.iter()).all(|(a, b)| a == b) } } impl std::cmp::Eq for DictValue {} impl std::hash::Hash for DictValue { fn hash<H: std::hash::Hasher>(&self, h: &mut H) { // IndexMap doesn't implement Hash so we need to provide our // own. It needs to match TypedValue::eq() which uses insertion // ordering so we'll do the same. for e in self.iter() { e.hash(h); } } } impl FromIterator<(ArrayKey, TypedValue)> for DictValue { fn from_iter<T>(iterator: T) -> Self where T: IntoIterator<Item = (ArrayKey, TypedValue)>, { Self(IndexMap::from_iter(iterator)) } } #[cfg(test)] mod test { use std::hash::BuildHasher; use super::*; use crate::StringInterner; #[test] fn test1() { let a = TypedValue::Keyset( [ArrayKey::Int(1), ArrayKey::Int(2), ArrayKey::Int(3)] .into_iter() .collect(), ); let b = TypedValue::Keyset( [ArrayKey::Int(3), ArrayKey::Int(2), ArrayKey::Int(1)] .into_iter() .collect(), ); assert_eq!(a, a); assert_ne!(a, b); let h = hash::BuildHasher::default(); assert_ne!(h.hash_one(a), h.hash_one(b)); } #[test] fn test2() { let a = TypedValue::Dict( [ (ArrayKey::Int(1), TypedValue::Int(10)), (ArrayKey::Int(2), TypedValue::Int(11)), (ArrayKey::Int(3), TypedValue::Int(12)), ] .into_iter() .collect(), ); let b = TypedValue::Dict( [ (ArrayKey::Int(3), TypedValue::Int(12)), (ArrayKey::Int(2), TypedValue::Int(11)), (ArrayKey::Int(1), TypedValue::Int(10)), ] .into_iter() .collect(), ); assert_eq!(a, a); assert_ne!(a, b); let h = hash::BuildHasher::default(); assert_ne!(h.hash_one(a), h.hash_one(b)); } #[test] fn test3() { let strings = StringInterner::default(); let a = TypedValue::Dict( [ ( ArrayKey::String(strings.intern_str("E")), TypedValue::Int(1), ), ( ArrayKey::String(strings.intern_str("F")), TypedValue::Int(1), ), ( ArrayKey::String(strings.intern_str("G")), TypedValue::Int(1), ), ( ArrayKey::String(strings.intern_str("H")), TypedValue::Int(1), ), ( ArrayKey::String(strings.intern_str("I")), TypedValue::Int(1), ), ] .into_iter() .collect(), ); let b = TypedValue::Dict(Default::default()); assert_eq!(a, a); assert_ne!(a, b); let h = hash::BuildHasher::default(); assert_ne!(h.hash_one(a), h.hash_one(b)); } }
Rust
hhvm/hphp/hack/src/hackc/ir/ir_core/types.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::fmt; use ffi::Str; use naming_special_names_rust as naming_special_names; use crate::newtype::ClassId; use crate::Attr; use crate::Attribute; use crate::SrcLoc; use crate::StringInterner; use crate::TypeConstraintFlags; use crate::TypedValue; use crate::UnitBytesId; // As a const fn, given a string removes the leading backslash. // r"\HH\AnyArray" -> r"HH\AnyArray". const fn strip_slash(name: &'static str) -> Str<'static> { Str::new(name.as_bytes().split_first().unwrap().1) } pub static BUILTIN_NAME_ANY_ARRAY: Str<'static> = strip_slash(naming_special_names::collections::ANY_ARRAY); pub static BUILTIN_NAME_ARRAYKEY: Str<'static> = strip_slash(naming_special_names::typehints::HH_ARRAYKEY); pub static BUILTIN_NAME_BOOL: Str<'static> = strip_slash(naming_special_names::typehints::HH_BOOL); pub static BUILTIN_NAME_CLASSNAME: Str<'static> = strip_slash(naming_special_names::classes::CLASS_NAME); pub static BUILTIN_NAME_DARRAY: Str<'static> = strip_slash(naming_special_names::typehints::HH_DARRAY); pub static BUILTIN_NAME_DICT: Str<'static> = strip_slash(naming_special_names::collections::DICT); pub static BUILTIN_NAME_FLOAT: Str<'static> = strip_slash(naming_special_names::typehints::HH_FLOAT); pub static BUILTIN_NAME_INT: Str<'static> = strip_slash(naming_special_names::typehints::HH_INT); pub static BUILTIN_NAME_KEYSET: Str<'static> = strip_slash(naming_special_names::collections::KEYSET); pub static BUILTIN_NAME_NONNULL: Str<'static> = strip_slash(naming_special_names::typehints::HH_NONNULL); pub static BUILTIN_NAME_NORETURN: Str<'static> = strip_slash(naming_special_names::typehints::HH_NORETURN); pub static BUILTIN_NAME_NOTHING: Str<'static> = strip_slash(naming_special_names::typehints::HH_NOTHING); pub static BUILTIN_NAME_NULL: Str<'static> = strip_slash(naming_special_names::typehints::HH_NULL); pub static BUILTIN_NAME_NUM: Str<'static> = strip_slash(naming_special_names::typehints::HH_NUM); pub static BUILTIN_NAME_RESOURCE: Str<'static> = strip_slash(naming_special_names::typehints::HH_RESOURCE); pub static BUILTIN_NAME_STRING: Str<'static> = strip_slash(naming_special_names::typehints::HH_STRING); pub static BUILTIN_NAME_THIS: Str<'static> = strip_slash(naming_special_names::typehints::HH_THIS); pub static BUILTIN_NAME_TYPENAME: Str<'static> = strip_slash(naming_special_names::classes::TYPE_NAME); pub static BUILTIN_NAME_VARRAY: Str<'static> = strip_slash(naming_special_names::typehints::HH_VARRAY); pub static BUILTIN_NAME_VARRAY_OR_DARRAY: Str<'static> = strip_slash(naming_special_names::typehints::HH_VARRAY_OR_DARRAY); pub static BUILTIN_NAME_VEC: Str<'static> = strip_slash(naming_special_names::collections::VEC); pub static BUILTIN_NAME_VEC_OR_DICT: Str<'static> = strip_slash(naming_special_names::typehints::HH_VEC_OR_DICT); pub static BUILTIN_NAME_VOID: Str<'static> = strip_slash(naming_special_names::typehints::HH_VOID); pub static BUILTIN_NAME_SOFT_VOID: Str<'static> = Str::new(br"@HH\void"); #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub enum BaseType { AnyArray, Arraykey, Bool, Class(ClassId), Classname, Darray, Dict, Float, Int, Keyset, Mixed, None, Nonnull, Noreturn, Nothing, Null, Num, Resource, String, This, Typename, Varray, VarrayOrDarray, Vec, VecOrDict, Void, } impl BaseType { pub fn write(&self, f: &mut fmt::Formatter<'_>, strings: &StringInterner) -> fmt::Result { match self { BaseType::AnyArray => f.write_str("AnyArray"), BaseType::Arraykey => f.write_str("Arraykey"), BaseType::Bool => f.write_str("Bool"), BaseType::Class(cid) => { write!(f, "Class(\"{}\")", cid.id.display(strings)) } BaseType::Classname => f.write_str("Classname"), BaseType::Darray => f.write_str("Darray"), BaseType::Dict => f.write_str("Dict"), BaseType::Float => f.write_str("Float"), BaseType::Int => f.write_str("Int"), BaseType::Keyset => f.write_str("Keyset"), BaseType::Mixed => f.write_str("Mixed"), BaseType::None => f.write_str("None"), BaseType::Nonnull => f.write_str("Nonnull"), BaseType::Noreturn => f.write_str("Noreturn"), BaseType::Nothing => f.write_str("Nothing"), BaseType::Null => f.write_str("Null"), BaseType::Num => f.write_str("Num"), BaseType::Resource => f.write_str("Resource"), BaseType::String => f.write_str("String"), BaseType::This => f.write_str("This"), BaseType::Typename => f.write_str("Typename"), BaseType::Varray => f.write_str("Varray"), BaseType::VarrayOrDarray => f.write_str("VarrayOrDarray"), BaseType::Vec => f.write_str("Vec"), BaseType::VecOrDict => f.write_str("VecOrDict"), BaseType::Void => f.write_str("Void"), } } } /// A basic type that is enforced by the underlying Hack runtime. /// /// Examples: /// Shapes are only enforcable as a darray - so a parameter which is specified /// as "shape('a' => int)" would have: /// ty: BaseType::Darray, /// modifiers: TypeConstraintFlags::ExtendedHint /// /// Nullable and int are fully enforcable - so a parameter which is specified /// as "?int" would have: /// ty: BaseType::Int, /// modifiers: TypeConstraintFlags::ExtendedHint | TypeConstraintFlags::Nullable /// #[derive(Debug, Clone, Eq, PartialEq, Hash)] pub struct EnforceableType { pub ty: BaseType, pub modifiers: TypeConstraintFlags, } impl EnforceableType { pub fn null() -> Self { EnforceableType { ty: BaseType::Null, modifiers: TypeConstraintFlags::NoFlags, } } pub fn write(&self, f: &mut fmt::Formatter<'_>, strings: &StringInterner) -> fmt::Result { f.write_str("Constraint { ty: ")?; self.ty.write(f, strings)?; f.write_str(", modifiers: ")?; if self.modifiers == TypeConstraintFlags::NoFlags { f.write_str("none")?; } else { let mut sep = ""; let mut check = |flag: TypeConstraintFlags, s: &str| { if self.modifiers.contains(flag) { write!(f, "{sep}{s}")?; sep = " | "; } Ok(()) }; check(TypeConstraintFlags::Nullable, "nullable")?; check(TypeConstraintFlags::Nullable, "case_type")?; check(TypeConstraintFlags::ExtendedHint, "extended_hint")?; check(TypeConstraintFlags::TypeVar, "type_var")?; check(TypeConstraintFlags::Soft, "soft")?; check(TypeConstraintFlags::TypeConstant, "type_constant")?; check(TypeConstraintFlags::Resolved, "resolved")?; check(TypeConstraintFlags::DisplayNullable, "display_nullable")?; check(TypeConstraintFlags::UpperBound, "upper_bound")?; } f.write_str(" }") } } impl Default for EnforceableType { fn default() -> Self { Self { ty: BaseType::None, modifiers: TypeConstraintFlags::NoFlags, } } } impl From<BaseType> for EnforceableType { fn from(ty: BaseType) -> Self { EnforceableType { ty, modifiers: TypeConstraintFlags::NoFlags, } } } /// A TypeInfo represents a type written by the user. It consists of the type /// written by the user (including generics) and an enforced constraint. #[derive(Clone, Debug, Default)] pub struct TypeInfo { /// The textual type that the user wrote including generics and special /// chars (like '?'). If None then this is directly computable from the /// enforced type. pub user_type: Option<UnitBytesId>, /// The underlying type this TypeInfo is constrained as. pub enforced: EnforceableType, } impl TypeInfo { pub fn empty() -> Self { Self { user_type: None, enforced: EnforceableType::default(), } } pub fn is_empty(&self) -> bool { matches!( self, TypeInfo { user_type: None, enforced: EnforceableType { ty: BaseType::None, modifiers: TypeConstraintFlags::NoFlags } } ) } pub fn write(&self, f: &mut fmt::Formatter<'_>, strings: &StringInterner) -> fmt::Result { f.write_str("TypeInfo { user_type: ")?; if let Some(ut) = self.user_type { write!(f, "\"{}\"", ut.display(strings))?; } else { f.write_str("none")?; } f.write_str(", constraint: ")?; self.enforced.write(f, strings)?; f.write_str("}") } pub fn display<'a>(&'a self, strings: &'a StringInterner) -> impl fmt::Display + 'a { struct D<'a> { strings: &'a StringInterner, self_: &'a TypeInfo, } impl fmt::Display for D<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.self_.write(f, self.strings) } } D { strings, self_: self, } } } impl From<EnforceableType> for TypeInfo { fn from(enforced: EnforceableType) -> TypeInfo { TypeInfo { user_type: None, enforced, } } } impl From<BaseType> for TypeInfo { fn from(ty: BaseType) -> TypeInfo { TypeInfo { user_type: None, enforced: ty.into(), } } } #[derive(Clone, Debug)] pub struct Typedef { pub name: ClassId, pub attributes: Vec<Attribute>, pub type_info_union: Vec<TypeInfo>, pub type_structure: TypedValue, pub loc: SrcLoc, pub attrs: Attr, pub case_type: bool, }
Rust
hhvm/hphp/hack/src/hackc/ir/ir_core/type_const.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use ffi::Str; use crate::TypedValue; #[derive(Debug)] pub struct TypeConstant<'a> { pub name: Str<'a>, pub initializer: Option<TypedValue>, pub is_abstract: bool, }
Rust
hhvm/hphp/hack/src/hackc/ir/ir_core/type_struct.rs
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. pub use hhvm_types_ffi::ffi::TypeStructureKind; use crate::ArrayKey; use crate::ClassId; use crate::StringInterner; use crate::TypedValue; #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub enum TypeStruct { Unresolved(ClassId), Null, Nonnull, } impl TypeStruct { pub fn into_typed_value(self, strings: &StringInterner) -> TypedValue { let kind_key = ArrayKey::String(strings.intern_str("kind")); match self { TypeStruct::Unresolved(cid) => { let kind = TypedValue::Int(TypeStructureKind::T_unresolved.repr as i64); let classname_key = ArrayKey::String(strings.intern_str("classname")); let name = TypedValue::String(cid.id); TypedValue::Dict( [(kind_key, kind), (classname_key, name)] .into_iter() .collect(), ) } TypeStruct::Null => { let kind = TypedValue::Int(TypeStructureKind::T_null.repr as i64); TypedValue::Dict([(kind_key, kind)].into_iter().collect()) } TypeStruct::Nonnull => { let kind = TypedValue::Int(TypeStructureKind::T_nonnull.repr as i64); TypedValue::Dict([(kind_key, kind)].into_iter().collect()) } } } pub fn try_from_typed_value(tv: &TypedValue, strings: &StringInterner) -> Option<TypeStruct> { let dv = tv.get_dict()?; let kind_key = ArrayKey::String(strings.intern_str("kind")); let kind = dv.get(&kind_key)?.get_int()?; if kind == i64::from(TypeStructureKind::T_null) { Some(TypeStruct::Null) } else if kind == i64::from(TypeStructureKind::T_nonnull) { Some(TypeStruct::Nonnull) } else if kind == i64::from(TypeStructureKind::T_unresolved) { let classname_key = ArrayKey::String(strings.intern_str("classname")); let classname = dv.get(&classname_key)?.get_string()?; let classname = strings.lookup_bytes_or_none(classname)?; let cid = ClassId::from_bytes(&classname, strings); Some(TypeStruct::Unresolved(cid)) } else { None } } } #[cfg(test)] mod test { use super::*; use crate::StringInterner; #[test] fn test1() { let strings = StringInterner::default(); assert_eq!( TypeStruct::try_from_typed_value( &TypeStruct::Null.into_typed_value(&strings), &strings ), Some(TypeStruct::Null) ); assert_eq!( TypeStruct::try_from_typed_value( &TypeStruct::Nonnull.into_typed_value(&strings), &strings ), Some(TypeStruct::Nonnull) ); let classname = strings.intern_str("ExampleClass"); let class_ts = TypeStruct::Unresolved(ClassId::new(classname)); assert_eq!( TypeStruct::try_from_typed_value( &class_ts.clone().into_typed_value(&strings), &strings ), Some(class_ts) ); } }
Rust
hhvm/hphp/hack/src/hackc/ir/ir_core/unit.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::sync::Arc; use bstr::BString; use ffi::Str; use crate::func::SrcLoc; use crate::string_intern::StringInterner; use crate::Attribute; use crate::Class; use crate::ClassName; use crate::ConstName; use crate::FatalOp; use crate::Function; use crate::FunctionName; use crate::HackConstant; use crate::IncludePath; use crate::Module; use crate::Typedef; #[derive(Debug, Default)] pub struct SymbolRefs<'a> { pub classes: Vec<ClassName<'a>>, pub constants: Vec<ConstName<'a>>, pub functions: Vec<FunctionName<'a>>, pub includes: Vec<IncludePath<'a>>, } /// Fields used when a unit had compile-time errors that should be reported /// when the unit is loaded. #[derive(Debug)] pub struct Fatal { pub op: FatalOp, pub loc: SrcLoc, pub message: BString, } /// Unit represents a single parsed file. #[derive(Debug, Default)] pub struct Unit<'a> { /// The list of classes defined in this Unit. This also includes enums which /// are transformed into classes internally. /// /// ``` /// class MyClass { ... } /// ``` pub classes: Vec<Class<'a>>, /// The list of top-level constants. /// /// ``` /// const MAGIC_VALUE: int = 42; /// ``` pub constants: Vec<HackConstant>, /// Per-file attributes. /// /// ``` /// <<file:__EnableUnstableFeatures('readonly')>> /// ``` pub file_attributes: Vec<Attribute>, /// The list of top-level functions defined in this Unit. This include both /// user-defined functions and "special" compiler-defined functions (like /// static initializers). /// /// ``` /// function my_fn(int $a, int $b) { ... } /// ``` pub functions: Vec<Function<'a>>, /// If the Unit failed to parse or compile this defines the error that /// should be reported and the rest of the Unit will be empty. // // NB: It could be argued that Unit should be an enum with Fatal/Success // being two separate variants. pub fatal: Option<Fatal>, pub modules: Vec<Module<'a>>, pub module_use: Option<Str<'a>>, /// The unit string interning table. pub strings: Arc<StringInterner>, /// The list of all external symbols referenced by this Unit. // // NB: We really should be able to generate this from the IR itself instead // of relying on a separate table. pub symbol_refs: SymbolRefs<'a>, /// The list of top-level typedefs or aliases defined in this Unit. /// /// ``` /// type A = B; /// ``` pub typedefs: Vec<Typedef>, }
TOML
hhvm/hphp/hack/src/hackc/ir/macros/Cargo.toml
# @generated by autocargo [package] name = "macros" version = "0.0.0" edition = "2021" [lib] path = "lib.rs" test = false doctest = false proc-macro = true [dependencies] proc-macro2 = { version = "1.0.64", features = ["span-locations"] } quote = "1.0.29" syn = { version = "1.0.109", features = ["extra-traits", "fold", "full", "visit", "visit-mut"] }
Rust
hhvm/hphp/hack/src/hackc/ir/macros/has_loc.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::borrow::Cow; use proc_macro2::Ident; use proc_macro2::Span; use proc_macro2::TokenStream; use quote::quote; use quote::ToTokens; use syn::spanned::Spanned; use syn::Attribute; use syn::Data; use syn::DataEnum; use syn::DataStruct; use syn::DeriveInput; use syn::Error; use syn::Lit; use syn::Meta; use syn::NestedMeta; use syn::Result; use syn::Variant; use crate::simple_type::SimpleType; use crate::util::InterestingFields; /// Builds a HasLoc impl. /// /// The build rules are as follows: /// - For a struct it just looks for a field with a type of LocId. /// - For an enum it does a match on each variant. /// - For either tuple variants or struct variants it looks for a field with a /// type of LocId. /// - For a tuple variant with a single non-LocId type and calls `.loc_id()` /// on that field. /// - Otherwise you can specify `#[has_loc(n)]` where `n` is the index of the /// field to call `.loc_id()` on. `#[has_loc(n)]` can also be used on the /// whole enum to provide a default index. /// pub(crate) fn build_has_loc(input: TokenStream) -> Result<TokenStream> { let input = syn::parse2::<DeriveInput>(input)?; match &input.data { Data::Enum(data) => build_has_loc_enum(&input, data), Data::Struct(data) => build_has_loc_struct(&input, data), Data::Union(_) => Err(Error::new(input.span(), "Union not handled")), } } fn field_might_contain_buried_loc_id(ty: &SimpleType<'_>) -> bool { if let Some(ident) = ty.get_ident() { !(ident == "BlockId" || ident == "ClassId" || ident == "ConstId" || ident == "ValueId" || ident == "LocalId" || ident == "MethodId" || ident == "ParamId" || ident == "VarId" || ident == "usize" || ident == "u32") } else { true } } fn build_has_loc_struct(input: &DeriveInput, data: &DataStruct) -> Result<TokenStream> { // struct Foo { // ... // loc: LocId, // } let struct_name = &input.ident; let default_select_field = handle_has_loc_attr(&input.attrs)?; let loc_field = if let Some(f) = default_select_field { match f.kind { FieldKind::Named(name) => { let name = name.to_string(); let field = data .fields .iter() .find(|field| field.ident.as_ref().map_or(false, |id| id == &name)) .ok_or_else(|| Error::new(input.span(), format!("Field '{name}' not found")))? .ident .as_ref() .unwrap(); quote!(#field.loc_id()) } FieldKind::None => todo!(), FieldKind::Numbered(_) => todo!(), } } else { let field = data .fields .iter() .enumerate() .map(|(i, field)| (i, field, SimpleType::from_type(&field.ty))) .find(|(_, _, ty)| ty.is_based_on("LocId")); let (idx, field, _) = field.ok_or_else(|| Error::new(input.span(), "No field with type LocId found"))?; if let Some(ident) = field.ident.as_ref() { ident.to_token_stream() } else { syn::Index::from(idx).to_token_stream() } }; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let output = quote!(impl #impl_generics HasLoc for #struct_name #ty_generics #where_clause { fn loc_id(&self) -> LocId { self.#loc_field } }); Ok(output) } fn get_select_field<'a>( variant: &'a Variant, default_select_field: &Option<Field<'a>>, ) -> Result<Option<Field<'a>>> { if let Some(f) = handle_has_loc_attr(&variant.attrs)? { return Ok(Some(f)); } if let Some(f) = default_select_field.as_ref() { return Ok(Some(f.clone())); } let mut interesting_fields = InterestingFields::None; for (idx, field) in variant.fields.iter().enumerate() { let ty = SimpleType::from_type(&field.ty); if ty.is_based_on("LocId") { let kind = if let Some(ident) = field.ident.as_ref() { // Bar { .., loc: LocId } FieldKind::Named(Cow::Borrowed(ident)) } else { // Bar(.., LocId) FieldKind::Numbered(idx) }; return Ok(Some(Field { kind, ty })); } else if field_might_contain_buried_loc_id(&ty) { // Report the type as 'unknown' because it's not a type that's // related to LocId. interesting_fields.add(idx, field.ident.as_ref(), SimpleType::Unknown); } } match interesting_fields { InterestingFields::None => { let kind = FieldKind::None; let ty = SimpleType::Unknown; Ok(Some(Field { kind, ty })) } InterestingFields::One(idx, ident, ty) => { // There's only a single field that could possibly contain a buried // LocId. let kind = ident.map_or_else( || FieldKind::Numbered(idx), |id| FieldKind::Named(Cow::Borrowed(id)), ); Ok(Some(Field { kind, ty })) } InterestingFields::Many => Ok(None), } } fn build_has_loc_enum(input: &DeriveInput, data: &DataEnum) -> Result<TokenStream> { // enum Foo { // Bar(.., LocId), // Baz { .., loc: LocId }, // } let default_select_field = handle_has_loc_attr(&input.attrs)?; let enum_name = &input.ident; let mut variants: Vec<TokenStream> = Vec::new(); for variant in data.variants.iter() { let select_field = get_select_field(variant, &default_select_field)?; if let Some(select_field) = select_field { push_handler(&mut variants, enum_name, variant, select_field); } else { return Err(Error::new( variant.span(), format!("LocId field not found in variant {}", variant.ident,), )); } } let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let output = quote!(impl #impl_generics HasLoc for #enum_name #ty_generics #where_clause { fn loc_id(&self) -> LocId { match self { #(#variants),* } } }); Ok(output) } #[derive(Clone)] struct Field<'a> { kind: FieldKind<'a>, ty: SimpleType<'a>, } #[derive(Clone)] enum FieldKind<'a> { Named(Cow<'a, Ident>), None, Numbered(usize), } fn push_handler( variants: &mut Vec<TokenStream>, enum_name: &Ident, variant: &Variant, field: Field<'_>, ) { let variant_name = &variant.ident; let reference = match (&field.kind, &field.ty) { (FieldKind::None, _) => quote!(LocId::NONE), (_, SimpleType::Unknown) => quote!(f.loc_id()), (_, SimpleType::Unit(_)) => quote!(*f), (_, SimpleType::Array(_)) | (_, SimpleType::BoxedSlice(_)) | (_, SimpleType::RefSlice(_)) | (_, SimpleType::Slice(_)) => { todo!("Unhandled type: {:?}", field.ty) } }; let params = match field.kind { FieldKind::Named(id) => { quote!( { #id: f, .. }) } FieldKind::None => match &variant.fields { syn::Fields::Named(_) => quote!({ .. }), syn::Fields::Unnamed(_) => quote!((..)), syn::Fields::Unit => TokenStream::default(), }, FieldKind::Numbered(idx) => { let mut fields = Vec::new(); for (field_idx, _) in variant.fields.iter().enumerate() { if field_idx == idx { fields.push(quote!(f)); } else { fields.push(quote!(_)); } } quote!((#(#fields),*)) } }; variants.push(quote!(#enum_name::#variant_name #params => #reference)); } fn handle_has_loc_attr(attrs: &[Attribute]) -> Result<Option<Field<'_>>> { for attr in attrs { if attr.path.is_ident("has_loc") { let meta = attr.parse_meta()?; match meta { Meta::Path(path) => { return Err(Error::new(path.span(), "Arguments expected")); } Meta::List(list) => { // has_loc(A, B, C) if list.nested.len() != 1 { return Err(Error::new(list.span(), "Only one argument expected")); } match &list.nested[0] { NestedMeta::Lit(Lit::Int(i)) => { return Ok(Some(Field { kind: FieldKind::Numbered(i.base10_parse()?), ty: SimpleType::Unknown, })); } NestedMeta::Lit(Lit::Str(n)) => { return Ok(Some(Field { kind: FieldKind::Named(Cow::Owned(Ident::new( &n.value(), Span::call_site(), ))), ty: SimpleType::Unknown, })); } NestedMeta::Meta(Meta::Path(meta)) if meta.is_ident("none") => { return Ok(Some(Field { kind: FieldKind::None, ty: SimpleType::Unknown, })); } i => { todo!("Unhandled: {:?}", i); } } } Meta::NameValue(_list) => { todo!(); } } } } Ok(None) }
Rust
hhvm/hphp/hack/src/hackc/ir/macros/has_locals.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::borrow::Cow; use proc_macro2::Ident; use proc_macro2::Span; use proc_macro2::TokenStream; use quote::quote; use syn::spanned::Spanned; use syn::Attribute; use syn::Data; use syn::DataEnum; use syn::DataStruct; use syn::DeriveInput; use syn::Error; use syn::Lit; use syn::Meta; use syn::NestedMeta; use syn::Result; use syn::Variant; use crate::simple_type::SimpleType; use crate::util::InterestingFields; /// Builds a HasLocals impl. /// pub(crate) fn build_has_locals(input: TokenStream) -> Result<TokenStream> { let input = syn::parse2::<DeriveInput>(input)?; match &input.data { Data::Enum(data) => build_has_locals_enum(&input, data), Data::Struct(data) => build_has_locals_struct(&input, data), Data::Union(_) => Err(Error::new(input.span(), "Union not handled")), } } fn field_might_contain_buried_local_id(ty: &SimpleType<'_>) -> bool { if let Some(ident) = ty.get_ident() { !(ident == "BlockId" || ident == "BareThisOp" || ident == "ClassId" || ident == "CmpOp" || ident == "CollectionType" || ident == "ConstId" || ident == "ContCheckOp" || ident == "FatalOp" || ident == "FunctionId" || ident == "IncDecOp" || ident == "InitPropOp" || ident == "IsTypeOp" || ident == "IterId" || ident == "LocId" || ident == "MethodId" || ident == "ParamId" || ident == "Predicate" || ident == "PropId" || ident == "ReadonlyOp" || ident == "SetOpOp" || ident == "SurpriseCheck" || ident == "TypeStructResolveOp" || ident == "UnitBytesId" || ident == "ValueId" || ident == "VarId" || ident == "u32" || ident == "usize") } else { true } } fn find_local_id_field<'a>(input: &'a DeriveInput, data: &'a DataStruct) -> Result<Field<'a>> { let mut fields: Vec<_> = data .fields .iter() .enumerate() .filter_map(|(i, field)| { let sty = SimpleType::from_type(&field.ty); if sty.is_based_on("LocalId") { Some((i, field, sty)) } else { None } }) .collect(); if fields.len() > 1 { return Err(Error::new( input.span(), format!( "Too many fields with LocalId type: [{}]", fields .iter() .map(|(i, _, _)| i.to_string()) .collect::<Vec<_>>() .join(", ") ), )); } let (idx, field, sty) = if let Some(info) = fields.pop() { info } else { let mut fields: Vec<_> = data .fields .iter() .enumerate() .filter_map(|(i, field)| { let sty = SimpleType::from_type(&field.ty); if matches!(sty, SimpleType::Unit(_)) { if field_might_contain_buried_local_id(&sty) { Some((i, field, sty)) } else { None } } else { None } }) .collect(); if fields.len() > 1 { return Err(Error::new( input.span(), format!( "Too many fields with possible LocalId type: [{}]", fields .iter() .map(|(i, _, _)| i.to_string()) .collect::<Vec<_>>() .join(", ") ), )); } if let Some(info) = fields.pop() { info } else { return Err(Error::new(input.span(), "No field could contain LocalId")); } }; let field = if let Some(ident) = field.ident.as_ref() { Field { kind: FieldKind::Named(Cow::Borrowed(ident)), ty: sty, } } else { Field { kind: FieldKind::Numbered(idx), ty: sty, } }; Ok(field) } fn build_has_locals_struct(input: &DeriveInput, data: &DataStruct) -> Result<TokenStream> { // struct Foo { // ... // lid: LocalId, // } let struct_name = &input.ident; let lid_field = { if let Some(f) = handle_has_locals_attr(&input.attrs)? { f } else { find_local_id_field(input, data)? } }; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let name = match lid_field { Field { kind: FieldKind::None, .. } => { quote!() } Field { kind: FieldKind::Named(ref name), .. } => quote!(self.#name), Field { kind: FieldKind::Numbered(idx), .. } => { let idx = syn::Index::from(idx); quote!(self.#idx) } }; let select = reference_for_ty(&lid_field.kind, &lid_field.ty, name, false); let output = quote!(impl #impl_generics HasLocals for #struct_name #ty_generics #where_clause { fn locals(&self) -> &[LocalId] { #select } }); // eprintln!("OUTPUT: {}", output); Ok(output) } fn get_select_field<'a>( variant: &'a Variant, default_select_field: &Option<Field<'a>>, ) -> Result<Option<Field<'a>>> { if let Some(f) = handle_has_locals_attr(&variant.attrs)? { return Ok(Some(f)); } if let Some(f) = default_select_field.as_ref() { return Ok(Some(f.clone())); } let mut interesting_fields = InterestingFields::None; for (idx, field) in variant.fields.iter().enumerate() { let ty = SimpleType::from_type(&field.ty); if ty.is_based_on("LocalId") { let kind = if let Some(ident) = field.ident.as_ref() { // Bar { .., lid: LocalId } FieldKind::Named(Cow::Borrowed(ident)) } else { // Bar(.., LocalId) FieldKind::Numbered(idx) }; return Ok(Some(Field { kind, ty })); } else if field_might_contain_buried_local_id(&ty) { // Report the type as 'unknown' because it's not a type that's // related to LocalId. interesting_fields.add(idx, field.ident.as_ref(), SimpleType::Unknown); } } // There are no explicit LocalId fields. let (kind, ty) = match interesting_fields { InterestingFields::None => { // There are no fields which might contain a buried LocalId. (FieldKind::None, SimpleType::Unknown) } InterestingFields::One(idx, ident, ty) => { // If there's only a single field that might contain a buried // LocalId. If it doesn't then the caller needs to be explicit. match ident { Some(ident) => (FieldKind::Named(Cow::Borrowed(ident)), ty), None => (FieldKind::Numbered(idx), ty), } } InterestingFields::Many => { // There are a bunch of fields which could contain a buried LocalId // - so we have no idea which to use. Caller needs to specify. return Ok(None); } }; Ok(Some(Field { kind, ty })) } fn build_has_locals_enum(input: &DeriveInput, data: &DataEnum) -> Result<TokenStream> { // enum Foo { // Bar(.., LocId), // Baz { .., loc: LocId }, // } let default_select_field = handle_has_locals_attr(&input.attrs)?; let enum_name = &input.ident; let mut variants: Vec<TokenStream> = Vec::new(); for variant in data.variants.iter() { let select_field = get_select_field(variant, &default_select_field)?; if let Some(select_field) = select_field { push_handler(&mut variants, enum_name, variant, select_field); } else { return Err(Error::new( variant.span(), format!("LocalId field not found in variant {}", variant.ident), )); } } let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let output = quote!(impl #impl_generics HasLocals for #enum_name #ty_generics #where_clause { fn locals(&self) -> &[LocalId] { match self { #(#variants),* } } }); // eprintln!("OUTPUT: {}", output); Ok(output) } #[derive(Clone, Debug)] struct Field<'a> { kind: FieldKind<'a>, ty: SimpleType<'a>, } #[derive(Clone, Debug)] enum FieldKind<'a> { Named(Cow<'a, Ident>), None, Numbered(usize), } fn reference_for_ty( kind: &FieldKind<'_>, ty: &SimpleType<'_>, name: TokenStream, is_ref: bool, ) -> TokenStream { match (kind, ty) { (FieldKind::None, _) => { quote!(&[]) } (_, SimpleType::Unit(_)) => { if is_ref { quote!(std::slice::from_ref(#name)) } else { quote!(std::slice::from_ref(&#name)) } } (_, SimpleType::Array(_)) | (_, SimpleType::BoxedSlice(_)) => { if is_ref { quote!(#name) } else { quote!(&#name) } } (_, SimpleType::Unknown) => { quote!(#name.locals()) } (_, SimpleType::RefSlice(_)) | (_, SimpleType::Slice(_)) => { todo!("Unhandled enum type: {:?}", ty) } } } fn push_handler( variants: &mut Vec<TokenStream>, enum_name: &Ident, variant: &Variant, field: Field<'_>, ) { let variant_name = &variant.ident; let reference = reference_for_ty(&field.kind, &field.ty, quote!(f), true); let params = match field.kind { FieldKind::Named(id) => { quote!( { #id: f, .. }) } FieldKind::None => match &variant.fields { syn::Fields::Named(_) => quote!({ .. }), syn::Fields::Unnamed(_) => quote!((..)), syn::Fields::Unit => TokenStream::default(), }, FieldKind::Numbered(idx) => { let mut fields = Vec::new(); for (field_idx, _) in variant.fields.iter().enumerate() { if field_idx == idx { fields.push(quote!(f)); } else { fields.push(quote!(_)); } } quote!((#(#fields),*)) } }; variants.push(quote!(#enum_name::#variant_name #params => #reference)); } fn handle_has_locals_attr(attrs: &[Attribute]) -> Result<Option<Field<'_>>> { for attr in attrs { if attr.path.is_ident("has_locals") { let meta = attr.parse_meta()?; match meta { Meta::Path(path) => { return Err(Error::new(path.span(), "Arguments expected")); } Meta::List(list) => { // locals(A, B, C) if list.nested.len() != 1 { return Err(Error::new(list.span(), "Only one argument expected")); } match &list.nested[0] { NestedMeta::Lit(Lit::Int(i)) => { return Ok(Some(Field { kind: FieldKind::Numbered(i.base10_parse()?), ty: SimpleType::Unknown, })); } NestedMeta::Lit(Lit::Str(n)) => { return Ok(Some(Field { kind: FieldKind::Named(Cow::Owned(Ident::new( &n.value(), Span::call_site(), ))), ty: SimpleType::Unknown, })); } NestedMeta::Meta(Meta::Path(meta)) if meta.is_ident("none") => { return Ok(Some(Field { kind: FieldKind::None, ty: SimpleType::Unknown, })); } i => { todo!("Unhandled: {:?}", i); } } } Meta::NameValue(_) => { todo!(); } } } } Ok(None) }
Rust
hhvm/hphp/hack/src/hackc/ir/macros/has_operands.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::borrow::Cow; use proc_macro2::Ident; use proc_macro2::Span; use proc_macro2::TokenStream; use quote::quote; use quote::ToTokens; use syn::spanned::Spanned; use syn::Attribute; use syn::Data; use syn::DataEnum; use syn::DataStruct; use syn::DeriveInput; use syn::Error; use syn::Lit; use syn::Meta; use syn::NestedMeta; use syn::Result; use syn::Variant; use crate::simple_type::SimpleType; use crate::util::InterestingFields; /// Builds a HasOperands impl. /// pub(crate) fn build_has_operands(input: TokenStream) -> Result<TokenStream> { let input = syn::parse2::<DeriveInput>(input)?; match &input.data { Data::Enum(data) => build_has_operands_enum(&input, data), Data::Struct(data) => build_has_operands_struct(&input, data), Data::Union(_) => Err(Error::new(input.span(), "Union not handled")), } } fn field_might_contain_buried_value_id(ty: &SimpleType<'_>) -> bool { if let Some(ident) = ty.get_ident() { !(ident == "BlockId" || ident == "ClassId" || ident == "ConstId" || ident == "LocId" || ident == "MethodId" || ident == "FunctionId" || ident == "LocalId" || ident == "ParamId" || ident == "PropId" || ident == "VarId" || ident == "usize" || ident == "u32") } else { true } } fn build_has_operands_struct(input: &DeriveInput, data: &DataStruct) -> Result<TokenStream> { // struct Foo { // ... // vid: ValueId, // } let struct_name = &input.ident; let field = data .fields .iter() .enumerate() .map(|(i, field)| (i, field, SimpleType::from_type(&field.ty))) .find(|(_, _, ty)| ty.is_based_on("ValueId")); let (idx, field, sty) = field.ok_or_else(|| Error::new(input.span(), "No field with type ValueId found"))?; let vid_field = if let Some(ident) = field.ident.as_ref() { ident.to_token_stream() } else { syn::Index::from(idx).to_token_stream() }; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); // The unit type here is guaranteed to be 'ValueId' let (getter, getter_mut) = match sty { SimpleType::BoxedSlice(_) => { // Box<[T]> let getter = quote!(&self.#vid_field); let getter_mut = quote!(&mut self.#vid_field); (getter, getter_mut) } SimpleType::Unit(_) => { // T let getter = quote!(std::slice::from_ref(&self.#vid_field)); let getter_mut = quote!(std::slice::from_mut(&mut self.#vid_field)); (getter, getter_mut) } SimpleType::Array(_) | SimpleType::Unknown | SimpleType::RefSlice(_) | SimpleType::Slice(_) => { todo!("Unhandled type: {:?}", sty) } }; let output = quote!(impl #impl_generics HasOperands for #struct_name #ty_generics #where_clause { fn operands(&self) -> &[ValueId] { #getter } fn operands_mut(&mut self) -> &mut [ValueId] { #getter_mut } }); // eprintln!("OUTPUT: {}", output); Ok(output) } fn get_select_field<'a>( variant: &'a Variant, default_select_field: &Option<Field<'a>>, ) -> Result<Option<Field<'a>>> { if let Some(f) = handle_has_operands_attr(&variant.attrs)? { return Ok(Some(f)); } if let Some(f) = default_select_field.as_ref() { return Ok(Some(f.clone())); } let mut interesting_fields = InterestingFields::None; for (idx, field) in variant.fields.iter().enumerate() { let ty = SimpleType::from_type(&field.ty); if ty.is_based_on("ValueId") { let kind = if let Some(ident) = field.ident.as_ref() { // Bar { .., vid: ValueId } FieldKind::Named(Cow::Borrowed(ident)) } else { // Bar(.., ValueId) FieldKind::Numbered(idx) }; return Ok(Some(Field { kind, ty })); } else if field_might_contain_buried_value_id(&ty) { // Report the type as 'unknown' because it's not a type that's // related to ValueId. interesting_fields.add(idx, field.ident.as_ref(), SimpleType::Unknown); } } // There are no explicit ValueId fields. let (kind, ty) = match interesting_fields { InterestingFields::None => { // There are no fields which might contain a buried ValueId. (FieldKind::None, SimpleType::Unknown) } InterestingFields::One(idx, ident, ty) => { // If there's only a single field that might contain a buried // ValueId. If it doesn't then the caller needs to be explicit. match ident { Some(ident) => (FieldKind::Named(Cow::Borrowed(ident)), ty), None => (FieldKind::Numbered(idx), ty), } } InterestingFields::Many => { // There are a bunch of fields which could contain a buried ValueId // - so we have no idea which to use. Caller needs to specify. return Ok(None); } }; Ok(Some(Field { kind, ty })) } fn build_has_operands_enum(input: &DeriveInput, data: &DataEnum) -> Result<TokenStream> { // enum Foo { // Bar(.., LocId), // Baz { .., loc: LocId }, // } let default_select_field = handle_has_operands_attr(&input.attrs)?; let enum_name = &input.ident; let mut variants: Vec<(TokenStream, TokenStream)> = Vec::new(); for variant in data.variants.iter() { let select_field = get_select_field(variant, &default_select_field)?; if let Some(select_field) = select_field { push_handler(&mut variants, enum_name, variant, select_field); } else { return Err(Error::new( variant.span(), format!("ValueId field not found in variant {}", variant.ident), )); } } let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let (variants, variants_mut): (Vec<TokenStream>, Vec<TokenStream>) = variants.into_iter().unzip(); let output = quote!(impl #impl_generics HasOperands for #enum_name #ty_generics #where_clause { fn operands(&self) -> &[ValueId] { match self { #(#variants),* } } fn operands_mut(&mut self) -> &mut [ValueId] { match self { #(#variants_mut),* } } }); // eprintln!("OUTPUT: {}", output); Ok(output) } #[derive(Clone)] struct Field<'a> { kind: FieldKind<'a>, ty: SimpleType<'a>, } #[derive(Clone)] enum FieldKind<'a> { Named(Cow<'a, Ident>), None, Numbered(usize), } fn push_handler( variants: &mut Vec<(TokenStream, TokenStream)>, enum_name: &Ident, variant: &Variant, field: Field<'_>, ) { let variant_name = &variant.ident; let (reference, reference_mut) = match (&field.kind, &field.ty) { (FieldKind::None, _) => { let reference = quote!(&[]); let reference_mut = quote!(&mut []); (reference, reference_mut) } (_, SimpleType::Unit(_)) => { let reference = quote!(std::slice::from_ref(f)); let reference_mut = quote!(std::slice::from_mut(f)); (reference, reference_mut) } (_, SimpleType::Array(_)) | (_, SimpleType::BoxedSlice(_)) => { let reference = quote!(f); let reference_mut = quote!(f); (reference, reference_mut) } (_, SimpleType::Unknown) => { let reference = quote!(f.operands()); let reference_mut = quote!(f.operands_mut()); (reference, reference_mut) } (_, SimpleType::RefSlice(_)) | (_, SimpleType::Slice(_)) => { todo!("Unhandled enum type: {:?}", field.ty) } }; let params = match field.kind { FieldKind::Named(id) => { quote!( { #id: f, .. }) } FieldKind::None => match &variant.fields { syn::Fields::Named(_) => quote!({ .. }), syn::Fields::Unnamed(_) => quote!((..)), syn::Fields::Unit => TokenStream::default(), }, FieldKind::Numbered(idx) => { let mut fields = Vec::new(); for (field_idx, _) in variant.fields.iter().enumerate() { if field_idx == idx { fields.push(quote!(f)); } else { fields.push(quote!(_)); } } quote!((#(#fields),*)) } }; variants.push(( quote!(#enum_name::#variant_name #params => #reference), quote!(#enum_name::#variant_name #params => #reference_mut), )); } fn handle_has_operands_attr(attrs: &[Attribute]) -> Result<Option<Field<'_>>> { for attr in attrs { if attr.path.is_ident("has_operands") { let meta = attr.parse_meta()?; match meta { Meta::Path(path) => { return Err(Error::new(path.span(), "Arguments expected")); } Meta::List(list) => { // operands(A, B, C) if list.nested.len() != 1 { return Err(Error::new(list.span(), "Only one argument expected")); } match &list.nested[0] { NestedMeta::Lit(Lit::Int(i)) => { return Ok(Some(Field { kind: FieldKind::Numbered(i.base10_parse()?), ty: SimpleType::Unknown, })); } NestedMeta::Lit(Lit::Str(n)) => { return Ok(Some(Field { kind: FieldKind::Named(Cow::Owned(Ident::new( &n.value(), Span::call_site(), ))), ty: SimpleType::Unknown, })); } NestedMeta::Meta(Meta::Path(meta)) if meta.is_ident("none") => { return Ok(Some(Field { kind: FieldKind::None, ty: SimpleType::Unknown, })); } i => { todo!("Unhandled: {:?}", i); } } } Meta::NameValue(_) => { todo!(); } } } } Ok(None) }
Rust
hhvm/hphp/hack/src/hackc/ir/macros/lib.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. mod has_loc; mod has_locals; mod has_operands; mod simple_type; mod util; use proc_macro::TokenStream; #[proc_macro_derive(HasLoc, attributes(has_loc))] pub fn has_loc_macro(input: TokenStream) -> TokenStream { match has_loc::build_has_loc(input.into()) { Ok(res) => res.into(), Err(err) => err.into_compile_error().into(), } } #[proc_macro_derive(HasLocals, attributes(has_locals))] pub fn has_locals_macro(input: TokenStream) -> TokenStream { match has_locals::build_has_locals(input.into()) { Ok(res) => res.into(), Err(err) => err.into_compile_error().into(), } } #[proc_macro_derive(HasOperands, attributes(has_operands))] pub fn has_operands_macro(input: TokenStream) -> TokenStream { match has_operands::build_has_operands(input.into()) { Ok(res) => res.into(), Err(err) => err.into_compile_error().into(), } }
Rust
hhvm/hphp/hack/src/hackc/ir/macros/operands.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::collections::HashSet; use hhbc::ImmType; use hhbc::InstrFlags; use hhbc::OpcodeData; use proc_macro2::Ident; use proc_macro2::Span; use proc_macro2::TokenStream; use quote::quote; use quote::ToTokens; use syn::spanned::Spanned; use syn::Attribute; use syn::Data; use syn::DataEnum; use syn::DataStruct; use syn::DeriveInput; use syn::Error; use syn::Lit; use syn::LitByteStr; use syn::LitStr; use syn::Meta; use syn::MetaList; use syn::MetaNameValue; use syn::NestedMeta; use syn::Path; use syn::Result; use syn::Variant; /// Builds a HasOperands impl. /// /// The build rules are as follows: /// //- For a struct it just looks for a field with a type of LocId. /// //- For an enum it does a match on each variant. /// // - For either tuple variants or struct variants it looks for a field with a /// // type of LocId. /// // - For a tuple variant with a single non-LocId type and calls `.loc_id()` /// // on that field. /// // - Otherwise you can specify `#[has_loc(n)]` where `n` is the index of the /// // field to call `.loc_id()` on. `#[has_loc(n)]` can also be used on the /// // whole enum to provide a default index. /// pub(crate) fn build_has_operands(input: TokenStream) -> Result<TokenStream> { let input = syn::parse2::<DeriveInput>(input)?; match &input.data { Data::Enum(data) => build_has_operands_enum(&input, data), Data::Struct(data) => build_has_operands_struct(&input, data), Data::Union(_) => Err(Error::new(input.span(), "Union not handled")), } } fn type_is_value_id(ty: &syn::Type) -> bool { match ty { syn::Type::Path(ty) => ty.path.is_ident("ValueId"), syn::Type::Reference(reference) => type_is_value_id(&reference.elem), _ => false, } } fn build_has_operands_struct(input: &DeriveInput, data: &DataStruct) -> Result<TokenStream> { todo!("build_has_operands_struct"); /* // struct Foo { // ... // loc: LocId, // } let struct_name = &input.ident; let field = data .fields .iter() .enumerate() .find(|(_, field)| type_is_loc_id(&field.ty)); let (idx, field) = if let Some((idx, field)) = field { (idx, field) } else { return Err(Error::new(input.span(), "No field with type LocId found")); }; let loc_field = if let Some(ident) = field.ident.as_ref() { ident.to_token_stream() } else { syn::Index::from(idx).to_token_stream() }; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let output = quote!(impl #impl_generics HasLoc for #struct_name #ty_generics #where_clause { fn loc_id(&self) -> LocId { self.#loc_field } }); Ok(output) */ } fn build_has_operands_enum(input: &DeriveInput, data: &DataEnum) -> Result<TokenStream> { // enum Foo { // Bar(.., LocId), // Baz { .., loc: LocId }, // } let default_select_field = handle_has_operands_attr(&input.attrs)?; let enum_name = &input.ident; let mut variants: Vec<TokenStream> = Vec::new(); for variant in data.variants.iter() { let variant_name = &variant.ident; let mut select_field = handle_has_operands_attr(&variant.attrs)?; if select_field.is_none() { for (idx, field) in variant.fields.iter().enumerate() { if type_is_value_id(&field.ty) { let kind = if let Some(ident) = field.ident.as_ref() { // Bar { .., vid: ValueId } FieldKind::Named(ident) } else { // Bar(.., ValueId) FieldKind::Numbered(idx) }; select_field = Some(Field { kind, direct: true }); break; } } } if select_field.is_none() && variant.fields.len() == 1 { // `Foo(field)` or `Foo{field: Ty}` let field = variant.fields.iter().next().unwrap(); if let Some(ident) = field.ident.as_ref() { todo!("named field"); } else { select_field = Some(Field { kind: FieldKind::Numbered(0), direct: false, }); } } let select_field = select_field.or(default_select_field.clone()); if let Some(select_field) = select_field { push_handler(&mut variants, enum_name, variant, select_field); } else { return Err(Error::new( variant.span(), format!("ValueId field not found in variant {}", variant.ident,), )); } } let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let output = quote!(impl #impl_generics HasOperands for #enum_name #ty_generics #where_clause { fn operands(&self) -> LocId { match self { #(#variants),* } } fn operands_mut(&mut self) -> &mut [ValueId] { todo!(); } }); Ok(output) } #[derive(Clone)] struct Field<'a> { kind: FieldKind<'a>, direct: bool, } #[derive(Clone)] enum FieldKind<'a> { Named(&'a Ident), None, Numbered(usize), } fn push_handler( variants: &mut Vec<TokenStream>, enum_name: &Ident, variant: &Variant, field: Field<'_>, ) { let variant_name = &variant.ident; let reference = if field.direct { quote!(*f) } else { quote!(f.operands()) }; match field.kind { FieldKind::Named(id) => { variants.push(quote!(#enum_name::#variant_name { #id: f, .. } => #reference)); } FieldKind::None => { variants.push(quote!(#enum_name::#variant_name(..) => LocId::NONE)); } FieldKind::Numbered(idx) => { let mut fields = Vec::new(); for (field_idx, _) in variant.fields.iter().enumerate() { if field_idx == idx { fields.push(quote!(f)); } else { fields.push(quote!(_)); } } variants.push(quote!(#enum_name::#variant_name(#(#fields),*) => #reference)); } } } fn handle_has_operands_attr(attrs: &[Attribute]) -> Result<Option<Field<'_>>> { for attr in attrs { if attr.path.is_ident("has_operands") { let meta = attr.parse_meta()?; match meta { Meta::Path(path) => { return Err(Error::new(path.span(), "Arguments expected")); } Meta::List(list) => { // has_operands(A, B, C) if list.nested.len() != 1 { return Err(Error::new(list.span(), "Only one argument expected")); } match &list.nested[0] { NestedMeta::Lit(Lit::Int(i)) => { return Ok(Some(Field { kind: FieldKind::Numbered(i.base10_parse()?), direct: false, })); } NestedMeta::Meta(Meta::Path(meta)) if meta.is_ident("none") => { return Ok(Some(Field { kind: FieldKind::None, direct: true, })); } i => { todo!("Unhandled: {:?}", i); } } } Meta::NameValue(list) => { todo!("C"); } } } } Ok(None) }
Rust
hhvm/hphp/hack/src/hackc/ir/macros/simple_type.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use proc_macro2::Ident; use syn::Path; #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) enum SimpleType<'a> { // [T; #] Array(&'a Ident), // Box<[T]> BoxedSlice(&'a Ident), // &[T] RefSlice(&'a Ident), // [T] Slice(&'a Ident), // T Unit(&'a Ident), Unknown, } impl<'a> SimpleType<'a> { pub(crate) fn get_ident(&self) -> Option<&'a Ident> { match self { SimpleType::Unknown => None, SimpleType::Unit(id) | SimpleType::Array(id) | SimpleType::BoxedSlice(id) | SimpleType::RefSlice(id) | SimpleType::Slice(id) => Some(id), } } pub(crate) fn is_based_on(&self, s: &str) -> bool { if let Some(id) = self.get_ident() { id == s } else { false } } pub(crate) fn from_type(ty: &'a syn::Type) -> SimpleType<'a> { match ty { syn::Type::Path(ty) => { let path = &ty.path; if let Some(id) = path.get_ident() { SimpleType::Unit(id) } else if let Some(box_ty) = get_box_ty(path) { let box_ty = SimpleType::from_type(box_ty); match box_ty { SimpleType::Slice(id) => { // Box<[T]> SimpleType::BoxedSlice(id) } SimpleType::Array(_) | SimpleType::BoxedSlice(_) | SimpleType::RefSlice(_) | SimpleType::Unit(_) | SimpleType::Unknown => { // Box<[T; #]> // Box<Box<[T]>> // Box<&[T]> // Box<T> SimpleType::Unknown } } } else { SimpleType::Unknown } } syn::Type::Reference(ref_ty) => { let ref_ty = SimpleType::from_type(&ref_ty.elem); match ref_ty { SimpleType::Slice(id) => { // &[T] SimpleType::RefSlice(id) } SimpleType::Array(_) | SimpleType::BoxedSlice(_) | SimpleType::RefSlice(_) | SimpleType::Unit(_) | SimpleType::Unknown => { // &[T; #] // &Box<[T]> // &&[T] // &T SimpleType::Unknown } } } syn::Type::Slice(slice_ty) => { let slice_ty = SimpleType::from_type(&slice_ty.elem); match slice_ty { SimpleType::Unit(id) => SimpleType::Slice(id), SimpleType::Array(_) | SimpleType::BoxedSlice(_) | SimpleType::RefSlice(_) | SimpleType::Slice(_) | SimpleType::Unknown => { // [[T; #]] // [Box<[T]>] // [&[T]] // [[T]] SimpleType::Unknown } } } syn::Type::Array(array_ty) => { let array_ty = SimpleType::from_type(&array_ty.elem); match array_ty { SimpleType::Unit(id) => SimpleType::Array(id), SimpleType::Array(_) | SimpleType::BoxedSlice(_) | SimpleType::RefSlice(_) | SimpleType::Slice(_) | SimpleType::Unknown => { // [[T; #]; #] // [Box<[T]>; #] // [&[T]; #] // [[T]; #] SimpleType::Unknown } } } _ => SimpleType::Unknown, } } } fn get_box_ty<'a>(path: &'a Path) -> Option<&'a syn::Type> { if path.segments.len() != 1 { return None; } let segment = &path.segments[0]; if segment.ident != "Box" { return None; } let generic_args = match &segment.arguments { syn::PathArguments::AngleBracketed(generic_args) => generic_args, _ => { return None; } }; let gty = generic_args.args.first()?; match gty { syn::GenericArgument::Type(ty) => Some(ty), _ => None, } }
Rust
hhvm/hphp/hack/src/hackc/ir/macros/util.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use proc_macro2::Ident; use crate::simple_type::SimpleType; pub(crate) enum InterestingFields<'a> { None, One(usize, Option<&'a Ident>, SimpleType<'a>), Many, } impl<'a> InterestingFields<'a> { pub(crate) fn add(&mut self, idx: usize, ident: Option<&'a Ident>, ty: SimpleType<'a>) { *self = match self { InterestingFields::None => InterestingFields::One(idx, ident, ty), InterestingFields::One(..) | InterestingFields::Many => InterestingFields::Many, } } }
Rust
hhvm/hphp/hack/src/hackc/ir/passes/async.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use ir_core::instr::Terminator; use ir_core::BlockId; use ir_core::Call; use ir_core::Func; use ir_core::FuncBuilder; use ir_core::Instr; /// Turn async calls into normal calls by following the eager return edge. /// /// Purposely leaves the HasAsyncEagerOffset flag set so later code can /// determine that this was originally an async call. pub fn unasync(func: &mut Func<'_>) { // Go through the blocks and rewrite: // // call_async(params) to lazy, eager // -> // %n = call(params) // jmp_arg eager(%n) // // And then let cleanup snap everything together. let mut changed = false; FuncBuilder::borrow_func_no_strings(func, |builder| { for bid in builder.func.block_ids() { builder.start_block(bid); // Steal the terminator so we can dissect it. let term = std::mem::replace(builder.func.terminator_mut(bid), Terminator::Unreachable); match term { Terminator::CallAsync(box call, [lazy, eager]) => { // Remove the (now unreachable) terminator from the block. changed = true; builder.cur_block_mut().iids.pop(); rewrite_async_call(builder, call, [lazy, eager]); } term => { *builder.func.terminator_mut(bid) = term; } } } }); if changed { crate::clean::run(func); } } fn rewrite_async_call(builder: &mut FuncBuilder<'_>, call: Call, [_lazy, eager]: [BlockId; 2]) { let loc = call.loc; let vid = builder.emit(Instr::call(call)); builder.emit(Instr::Terminator(Terminator::JmpArgs( eager, Box::new([vid]), loc, ))); } #[cfg(test)] mod test { use std::sync::Arc; use testutils::build_test_func; use testutils::build_test_func_with_strings; use testutils::Block; use super::*; #[test] fn basic() { let (mut f1, strings) = build_test_func(&[ Block::call_async("b0", "bar", ["b1", "b4"]), Block::jmp_op("b1", ["b2", "b3"]).with_param("p1"), Block::jmp_arg("b2", "b5", "p1"), Block::jmp_arg("b3", "b5", "p5").with_named_target("p5"), Block::jmp_arg("b4", "b5", "p7").with_param("p7"), Block::ret_value("b5", "p9").with_param("p9"), ]); unasync(&mut f1); let f2 = build_test_func_with_strings( &[Block::ret_value("b0", "p0").with_named_target("p0")], Arc::clone(&strings), ); testutils::assert_func_struct_eq(&f1, &f2, &strings); } }
TOML
hhvm/hphp/hack/src/hackc/ir/passes/Cargo.toml
# @generated by autocargo [package] name = "passes" version = "0.0.0" edition = "2021" [lib] path = "lib.rs" [dependencies] analysis = { version = "0.0.0", path = "../analysis" } ir_core = { version = "0.0.0", path = "../ir_core" } itertools = "0.10.3" log = { version = "0.4.17", features = ["kv_unstable", "kv_unstable_std"] } newtype = { version = "0.0.0", path = "../../../utils/newtype" } print = { version = "0.0.0", path = "../print" } [dev-dependencies] ffi = { version = "0.0.0", path = "../../../utils/ffi" } hash = { version = "0.0.0", path = "../../../utils/hash" } rand = { version = "0.8", features = ["small_rng"] } testutils = { version = "0.0.0", path = "../testutils" } verify = { version = "0.0.0", path = "../verify" }
Rust
hhvm/hphp/hack/src/hackc/ir/passes/clean.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use analysis::PredecessorCatchMode; use analysis::PredecessorFlags; use analysis::Predecessors; use ir_core::instr::HasOperands; use ir_core::instr::Terminator; use ir_core::BlockId; use ir_core::Func; use ir_core::Instr; use ir_core::InstrId; use ir_core::ValueId; use ir_core::ValueIdMap; use itertools::Itertools; use log::trace; use newtype::IdVec; use print::FmtRawVid; /// Attempt to clean a Func by doing several clean-up steps: /// - merge simple jumps /// - rpo_sort /// - remove common JmpArgs parameters /// - renumber Instrs /// - remove unreferenced Instrs. pub fn run<'a>(func: &mut Func<'a>) { // Start with RPO which will DCE as a side-effect. crate::rpo_sort(func); // Remove unnecessary block params. remove_common_args(func); // Snap through jumps. merge_simple_jumps(func); // Re-RPO (since the structure may have changed). crate::rpo_sort(func); // Finally renumber all the Instrs. renumber(func); } /// Go through the blocks. Any blocks that are connected by a singular edge are /// merged. fn merge_simple_jumps(func: &mut Func<'_>) { let predecessors = analysis::compute_predecessor_blocks( func, PredecessorFlags { mark_entry_blocks: true, catch: PredecessorCatchMode::Throw, }, ); for bid in func.block_ids() { loop { let terminator = func.get_terminator(bid); match terminator { Some(Terminator::Jmp(target_bid, _)) => { let target_bid = *target_bid; if (func.block(bid).tcid == func.block(target_bid).tcid) && (predecessors[&target_bid].len() == 1) { // Steal the target's iids. If the target is later then // it will show as having no terminator. let target_iids = std::mem::take(&mut func.block_mut(target_bid).iids); let block = func.block_mut(bid); // ...remove the terminator block.iids.pop(); // ...amend the target block. block.iids.extend(target_iids.into_iter()); // Don't need to update the predecessors - since we only // check that there is only a single predecessor that // will still be true when we check the new terminator. continue; } } _ => {} } break; } } } /// Go through a Func and for any BlockParam that is passed the same value from /// all callers snap the value through to the passed value and remove the /// BlockParam. fn remove_common_args(func: &mut Func<'_>) { // TODO: This algorithm could be a lot smarter about when it needs to // reprocess a block. let predecessors = analysis::compute_predecessor_blocks( func, PredecessorFlags { mark_entry_blocks: false, catch: PredecessorCatchMode::FromNone, }, ); let mut remap: IdVec<InstrId, ValueId> = IdVec::new_from_vec( (0..func.instrs.len()) .map(|iid| ValueId::from_instr(InstrId::from_usize(iid))) .collect(), ); let mut changed = true; while changed { changed = false; for bid in func.block_ids() { if func.block(bid).params.is_empty() { continue; } trace!("Block: {}", bid); let common_params = compute_common_args(func, &mut remap, bid, &predecessors); trace!(" result = {:?}", common_params); match common_params { CommonArgs::Ignore => { // Ignore this block. } CommonArgs::CatchArgs => { // There should be exactly one arg. } CommonArgs::NoCommon => { // Nothing to do - everything is an arg. } CommonArgs::AllCommon(common_params) => { // Everything is common - turn the predecessors into a // simple Jmp and zap the params. Don't forget to remap the // params to the common args. if let Some(preds) = predecessors.get(&bid) { for &pred in preds.iter() { let terminator = func.terminator_mut(pred); match *terminator { Terminator::JmpArgs(target, _, loc) => { *terminator = Terminator::Jmp(target, loc); } _ => unreachable!(), } } } let block = func.block_mut(bid); for (param, common) in block.params.drain(..).zip(common_params.into_iter()) { trace!(" remap: {} => {}", param, FmtRawVid(common)); remap[param] = common; } } CommonArgs::SomeCommon(common_params) => { trace!( " common: [{}]", common_params .iter() .map(|&vid| FmtRawVid(vid).to_string()) .join(", ") ); let mut remove = Vec::with_capacity(common_params.len()); for (i, (&param, common)) in func .block(bid) .params .iter() .zip(common_params.into_iter()) .enumerate() .filter(|(_, (_, common))| !common.is_none()) { trace!(" remap: {} => {}", param, FmtRawVid(common)); remap[param] = common; remove.push(i); } if !remove.is_empty() { changed = true; } // Remove the unused args from the predecessors. if let Some(preds) = predecessors.get(&bid) { for &pred in preds.iter() { let terminator = func.terminator_mut(pred); match terminator { Terminator::JmpArgs(_, old_values, _) => { let values = remove_multi( old_values.iter().copied(), remove.iter().copied(), ) .collect_vec(); *old_values = values.into_boxed_slice(); } _ => unreachable!(), } } } // Remove the unused args from the block params. let params = &mut func.block_mut(bid).params; *params = remove_multi(params.iter().copied(), remove.iter().copied()).collect(); } } } } let remap_vids: ValueIdMap<ValueId> = remap .into_iter() .enumerate() .filter_map(|(src_idx, dst)| { let src = ValueId::from_instr(InstrId::from_usize(src_idx)); if src == dst { None } else { Some((src, dst)) } }) .collect(); func.remap_vids(&remap_vids); } /// Produce an iterator with the indices of `remove` removed. `remove` must be /// sorted. /// /// For example: /// remove_multi([1, 2, 3, 4, 5, 6].iter(), [1, 3].iter()) /// would return `[1, 3, 5, 6].iter()` /// #[allow(unreachable_code, unused_variables)] fn remove_multi<T, I, R>(input: I, remove: R) -> impl Iterator<Item = T> where I: Iterator<Item = T>, R: Iterator<Item = usize>, { let mut last_remove: Option<usize> = None; let mut remove = remove.peekable(); input.enumerate().filter_map(move |(i, value)| { if Some(&i) == remove.peek() { // Ensure that 'remove' was actually sorted... debug_assert!(last_remove.map_or(true, |last| last <= i)); last_remove = Some(i); remove.next(); None } else { Some(value) } }) } #[derive(Debug)] enum CommonArgs { Ignore, CatchArgs, NoCommon, AllCommon(Vec<ValueId>), // Common args are marked as the common value. Mixed args are marked with // ValueId::none(). SomeCommon(Vec<ValueId>), } fn compute_common_args( func: &Func<'_>, remap: &mut IdVec<InstrId, ValueId>, bid: BlockId, predecessors: &Predecessors, ) -> CommonArgs { if let Some(preds) = predecessors.get(&bid) { trace!( " Predecessors: [{}]", preds.iter().map(|bid| bid.to_string()).join(", ") ); let mut pred_iter = preds.iter().copied(); if let Some(first_pred) = pred_iter.next() { if first_pred == BlockId::NONE { // This is a catch block. return CommonArgs::CatchArgs; } let pred_terminator = func.terminator(first_pred); if !matches!(pred_terminator, Terminator::JmpArgs(..)) { // The predecessor is not a JmpArgs - we can't do anything here. return CommonArgs::Ignore; } let mut common_params = pred_terminator .operands() .iter() .map(|&iid| lookup(remap, iid)) .collect_vec(); let mut all_common = true; let mut some_common = false; trace!( " pred {}: args [{}]", first_pred, common_params .iter() .map(|&vid| FmtRawVid(vid).to_string()) .join(", ") ); for next_pred in pred_iter { let next_terminator = func.terminator(next_pred); if !matches!(next_terminator, Terminator::JmpArgs(..)) { // The predecessor is not a JmpArgs - we can't do anything here. return CommonArgs::Ignore; } let next_params = next_terminator.operands(); trace!( " pred {}: args [{}]", next_pred, next_params .iter() .map(|&vid| FmtRawVid(lookup(remap, vid)).to_string()) .join(", ") ); for (idx, &iid) in next_params.iter().enumerate() { if common_params[idx] != lookup(remap, iid) { common_params[idx] = ValueId::none(); all_common = false; } else { some_common = true; } } } match (all_common, some_common) { (false, false) => CommonArgs::NoCommon, (false, true) => CommonArgs::SomeCommon(common_params), (true, _) => CommonArgs::AllCommon(common_params), } } else { // No predecessors - ignore it CommonArgs::Ignore } } else { // No predecessors - ignore it CommonArgs::Ignore } } fn lookup(remap: &mut IdVec<InstrId, ValueId>, vid: ValueId) -> ValueId { if let Some(iid) = vid.instr() { let repl = remap[iid]; if repl != ValueId::from_instr(iid) { // We found a replacement (rare), so go ahead and do the extra // work of following and optimizing the replacement chain. let mut prev = iid; let mut cur = repl; while let Some(cur_instr) = cur.instr() { let next = remap[cur_instr]; if next != cur { // This is a multi-hop chain (very rare). // // At this point we have the chain: prev -> cur -> next. // Shorten it as in union-find path splitting to speed // future lookups by making prev point directly to next. remap[prev] = next; prev = cur_instr; cur = next; } else { break; } } cur } else { repl } } else { vid } } fn renumber(func: &mut Func<'_>) { let mut remap: ValueIdMap<ValueId> = ValueIdMap::default(); let mut src_instrs = std::mem::take(&mut func.instrs); let mut dst_instrs: IdVec<InstrId, Instr> = IdVec::with_capacity(func.instrs_len()); for bid in func.block_ids() { let block = func.block_mut(bid); block.params = remapper(&mut remap, &mut src_instrs, &block.params, &mut dst_instrs); block.iids = remapper(&mut remap, &mut src_instrs, &block.iids, &mut dst_instrs); } func.instrs = dst_instrs; func.remap_vids(&remap); } fn remapper( remap: &mut ValueIdMap<ValueId>, src_instrs: &mut IdVec<InstrId, Instr>, src_iids: &[InstrId], dst_instrs: &mut IdVec<InstrId, Instr>, ) -> Vec<InstrId> { let mut expected_iid = InstrId::from_usize(dst_instrs.len()); let mut dst_iids = Vec::new(); for &iid in src_iids { if iid != expected_iid { remap.insert(ValueId::from_instr(iid), ValueId::from_instr(expected_iid)); } let instr = std::mem::replace(&mut src_instrs[iid], Instr::tombstone()); dst_instrs.push(instr); dst_iids.push(expected_iid); expected_iid.0 += 1; } dst_iids } #[cfg(test)] mod test { use std::sync::Arc; use testutils::build_test_func; use testutils::build_test_func_with_strings; use testutils::Block; use super::*; #[test] fn test_lookup() { let mut remap: IdVec<InstrId, ValueId> = IdVec::new_from_vec( (0..10) .map(|iid| ValueId::from_instr(InstrId::from_usize(iid))) .collect(), ); fn iid(n: usize) -> InstrId { InstrId::from_usize(n) } fn vid(n: usize) -> ValueId { ValueId::from_instr(InstrId::from_usize(n)) } assert_eq!(lookup(&mut remap, vid(0)), vid(0)); assert_eq!(lookup(&mut remap, vid(1)), vid(1)); remap[iid(2)] = vid(5); remap[iid(5)] = vid(6); assert_eq!(lookup(&mut remap, vid(2)), vid(6)); assert_eq!(lookup(&mut remap, vid(2)), vid(6)); remap[iid(6)] = vid(7); assert_eq!(lookup(&mut remap, vid(2)), vid(7)); } #[test] fn test_snap() { let (mut f1, strings) = build_test_func(&[ Block::jmp_arg("b0", "b4", "p0").with_named_target("p0"), Block::jmp_op("b1", ["b2", "b3"]).with_param("p3"), Block::jmp_arg("b2", "b5", "p3"), Block::jmp_arg("b3", "b5", "p6").with_named_target("p6"), Block::jmp_arg("b4", "b5", "p8").with_param("p8"), Block::ret_value("b5", "p10").with_param("p10"), ]); run(&mut f1); let f2 = build_test_func_with_strings( &[Block::ret_value("b0", "p0").with_named_target("p0")], Arc::clone(&strings), ); testutils::assert_func_struct_eq(&f1, &f2, &strings); } }
Rust
hhvm/hphp/hack/src/hackc/ir/passes/control.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use analysis::PredecessorCatchMode; use analysis::PredecessorFlags; use ir_core::instr::HasEdges; use ir_core::instr::Terminator; use ir_core::BlockId; use ir_core::BlockIdMap; use ir_core::Func; use ir_core::InstrId; use ir_core::ValueId; use newtype::IdVec; /// Attempt to merge simple blocks together. Returns true if the Func was /// changed. pub fn run(func: &mut Func<'_>) -> bool { let mut changed = false; let mut predecessors = analysis::compute_num_predecessors( func, PredecessorFlags { mark_entry_blocks: false, catch: PredecessorCatchMode::Throw, }, ); for bid in func.block_ids().rev() { let mut instr = std::mem::replace(func.terminator_mut(bid), Terminator::Unreachable); let edges = instr.edges_mut(); let successors = edges.len() as u32; for edge in edges { if let Some(target) = forward_edge(func, *edge, successors, &predecessors) { changed = true; predecessors[*edge] -= 1; predecessors[target] += 1; *edge = target; } } *func.terminator_mut(bid) = instr; } // Function params for idx in 0..func.params.len() { if let Some(dv) = func.params[idx].default_value { if let Some(target) = forward_edge(func, dv.init, 1, &predecessors) { changed = true; predecessors[dv.init] -= 1; predecessors[target] += 1; func.params[idx].default_value.as_mut().unwrap().init = target; } } } // Entry Block if let Some(target) = forward_edge(func, Func::ENTRY_BID, 1, &predecessors) { // Uh oh - we're remapping the ENTRY_BID - this is no good. Instead // remap the target and swap the two blocks. changed = true; let mut remap = BlockIdMap::default(); remap.insert(target, Func::ENTRY_BID); func.remap_bids(&remap); func.blocks.swap(Func::ENTRY_BID, target); } if changed { crate::rpo_sort(func); true } else { false } } fn params_eq(a: &[InstrId], b: &[ValueId]) -> bool { a.len() == b.len() && a.iter() .zip(b.iter()) .all(|(a, b)| ValueId::from_instr(*a) == *b) } fn forward_edge( func: &Func<'_>, mut bid: BlockId, mut predecessor_successors: u32, predecessors: &IdVec<BlockId, u32>, ) -> Option<BlockId> { // If the target block (bid) just contains a jump to another block then jump // directly to that one instead - but we need to worry about creating a // critical edge. If our predecessor has multiple successors and our target // has multiple predecessors then we can't combine them because that would // be a critical edge. // TODO: Optimize this. Nothing will break if this is too small or too // big. Too small means we'll snap through fewer chains. To big means we'll // take longer than necessary to bail on an infinite loop (which shouldn't // really happen normally). const LOOP_CHECK: usize = 100; let mut changed = false; for _ in 0..LOOP_CHECK { let block = func.block(bid); if block.iids.len() != 1 { // This block has multiple instrs. break; } let terminator = func.terminator(bid); let target = match *terminator { Terminator::Jmp(target, _) => { if !block.params.is_empty() { // The block takes params but the jump doesn't pass them // along - it's not a simple forward. break; } target } Terminator::JmpArgs(target, ref args, _) => { if !params_eq(&block.params, args) { // Our jump is passing a different set of args from what our // block takes in. break; } target } _ => { break; } }; let target_block = func.block(target); if target_block.tcid != block.tcid { // This jump crosses an exception frame - can't forward. break; } // Critical edges: If the predecessor has multiple successors and the // target has multiple predecessors then we can't continue any further // because it would create a critical edge. if predecessor_successors > 1 && predecessors[target] > 1 { break; } bid = target; changed = true; // We know that the next time through our predecessor must have had only // a single successor (since we checked for Jmp and JmpArgs above). predecessor_successors = 1; } changed.then_some(bid) } #[cfg(test)] mod test { use std::sync::Arc; use ir_core::func::DefaultValue; use ir_core::BlockId; use ir_core::Instr; use ir_core::InstrId; use ir_core::Param; use ir_core::StringInterner; use ir_core::TypeInfo; fn mk_param<'a>(name: &str, dv: BlockId, strings: &StringInterner) -> Param<'a> { Param { name: strings.intern_str(name), is_variadic: false, is_inout: false, is_readonly: false, user_attributes: vec![], ty: TypeInfo::default(), default_value: Some(DefaultValue { init: dv, expr: ffi::Str::new(b"1"), }), } } #[test] fn test1() { // Can't forward because 'b' isn't empty. let (mut func, strings) = testutils::build_test_func(&[ testutils::Block::jmp("a", "b").with_target(), testutils::Block::jmp("b", "c").with_target(), testutils::Block::ret("c"), ]); let expected = func.clone(); let changed = super::run(&mut func); assert!(!changed); testutils::assert_func_struct_eq(&func, &expected, &strings); } #[test] fn test2() { // 'a' forwards directly to 'c' let (mut func, strings) = testutils::build_test_func(&[ testutils::Block::jmp("a", "b").with_target(), testutils::Block::jmp("b", "c"), testutils::Block::ret("c").with_target(), ]); let changed = super::run(&mut func); assert!(changed); let expected = testutils::build_test_func_with_strings( &[ testutils::Block::jmp("a", "c").with_target(), testutils::Block::ret("c").with_target(), ], Arc::clone(&strings), ); testutils::assert_func_struct_eq(&func, &expected, &strings); } #[test] fn test3() { // Can't forward because it would create a critical section. let (mut func, strings) = testutils::build_test_func(&[ testutils::Block::jmp_op("a", ["b", "c"]).with_target(), testutils::Block::jmp("b", "d"), testutils::Block::jmp("c", "d"), testutils::Block::ret("d").with_target(), ]); let expected = func.clone(); let changed = super::run(&mut func); assert!(!changed); testutils::assert_func_struct_eq(&func, &expected, &strings); } #[test] fn test4() { // Expect 'c' to be forwarded directly to 'e'. let (mut func, strings) = testutils::build_test_func(&[ testutils::Block::jmp_op("a", ["b", "c"]).with_target(), testutils::Block::jmp("b", "e"), testutils::Block::jmp("c", "d"), testutils::Block::jmp("d", "e"), testutils::Block::ret("e").with_target(), ]); let changed = super::run(&mut func); assert!(changed); let expected = testutils::build_test_func_with_strings( &[ testutils::Block::jmp_op("a", ["b", "c"]).with_target(), testutils::Block::jmp("b", "e"), testutils::Block::jmp("c", "e"), testutils::Block::ret("e").with_target(), ], Arc::clone(&strings), ); testutils::assert_func_struct_eq(&func, &expected, &strings); } #[test] fn test5() { // Expect 'entry' to be removed. let (mut func, strings) = testutils::build_test_func(&[ testutils::Block::jmp("entry", "b"), testutils::Block::jmp("b", "c").with_target(), testutils::Block::ret("c"), ]); let changed = super::run(&mut func); assert!(changed); let expected = testutils::build_test_func_with_strings( &[ testutils::Block::jmp("b", "c").with_target(), testutils::Block::ret("c"), ], Arc::clone(&strings), ); testutils::assert_func_struct_eq(&func, &expected, &strings); } #[test] fn test6() { // We can forward c -> e but still need b -> d -> e because of critedge. let (mut func, strings) = testutils::build_test_func(&[ testutils::Block::jmp_op("a", ["b", "c"]), testutils::Block::jmp_op("b", ["d", "e"]), testutils::Block::jmp("c", "d"), testutils::Block::jmp("d", "e"), testutils::Block::ret("e"), ]); let changed = super::run(&mut func); assert!(changed); let expected = testutils::build_test_func_with_strings( &[ testutils::Block::jmp_op("a", ["b", "c"]), testutils::Block::jmp_op("b", ["d", "e"]), testutils::Block::jmp("c", "e"), testutils::Block::jmp("d", "e"), testutils::Block::ret("e"), ], Arc::clone(&strings), ); testutils::assert_func_struct_eq(&func, &expected, &strings); } #[test] fn test7() { // We expect to skip 'b' and 'c' let (mut func, strings) = testutils::build_test_func(&[ testutils::Block::jmp_op("a", ["b", "c"]), testutils::Block::jmp("b", "d"), testutils::Block::jmp("c", "e"), testutils::Block::ret("d"), testutils::Block::ret("e"), ]); let changed = super::run(&mut func); assert!(changed); let expected = testutils::build_test_func_with_strings( &[ testutils::Block::jmp_op("a", ["d", "e"]), testutils::Block::ret("d"), testutils::Block::ret("e"), ], Arc::clone(&strings), ); testutils::assert_func_struct_eq(&func, &expected, &strings); } #[test] fn test8() { // We expect to skip the entry block. let (mut func, strings) = testutils::build_test_func(&[ testutils::Block::jmp("a", "c"), testutils::Block::jmp("b", "c"), testutils::Block::jmp_op("c", ["d", "e"]), testutils::Block::ret("d"), testutils::Block::ret("e"), ]); func.params.push(mk_param("x", BlockId(1), &strings)); *func.instr_mut(InstrId(1)) = Instr::enter(BlockId(2), ir_core::LocId::NONE); eprintln!("FUNC:\n{}", print::DisplayFunc::new(&func, true, &strings)); let changed = super::run(&mut func); assert!(changed); let mut expected = testutils::build_test_func_with_strings( &[ testutils::Block::jmp_op("c", ["d", "e"]), testutils::Block::jmp("b", "c"), testutils::Block::ret("d"), testutils::Block::ret("e"), ], Arc::clone(&strings), ); expected.params.push(mk_param("x", BlockId(1), &strings)); *expected.instr_mut(InstrId(1)) = Instr::enter(BlockId(0), ir_core::LocId::NONE); testutils::assert_func_struct_eq(&func, &expected, &strings); } }
Rust
hhvm/hphp/hack/src/hackc/ir/passes/critedge.rs
use analysis::PredecessorCatchMode; use analysis::PredecessorFlags; use ir_core::instr::HasEdges; use ir_core::instr::HasLoc; use ir_core::Block; use ir_core::BlockId; use ir_core::Func; use ir_core::Instr; use ir_core::LocId; /// Find and split critical edges. Assumes there are no unreachable blocks, /// which is the case after rpo_sort(). /// /// A critical edge is one where the source has multiple successors and the /// destination has multiple predecessors. By splitting them we ensure that we /// can always add instructions to one side of an edge which only affects that /// edge. /// /// 1. find critical edges, build a simple work list. Create new BlockIds now /// and update the edges to the new target BlockIds. /// 2. Create the new empty blocks, then fill them in from the worklist. Order /// doesn't matter because we recorded all BlockIds in step 1. /// 3. re-run rpo_sort(). /// pub fn split_critical_edges(func: &mut Func<'_>, rpo_sort: bool) { let pred_counts = analysis::compute_num_predecessors( func, PredecessorFlags { mark_entry_blocks: false, catch: PredecessorCatchMode::Ignore, }, ); let mut work = Vec::new(); let num_blocks = func.blocks.len(); for bid in func.block_ids() { let term = func.terminator_mut(bid); let loc = term.loc_id(); let edges = term.edges_mut(); if edges.len() > 1 { for edge in edges { if pred_counts[*edge] > 1 { // cannot create new blocks and instructions while iterating // here, so make a simple worklist let split_bid = BlockId((num_blocks + work.len()) as u32); work.push(WorkItem { loc, split_bid, old_target: edge.clone(), }); *edge = split_bid; } } } } if !work.is_empty() { func.blocks .resize(num_blocks + work.len(), Block::default()); for item in work.drain(..) { let _params = func.block(item.old_target).params.len(); let instr = Instr::jmp(item.old_target, item.loc); func.emit(item.split_bid, instr); } if rpo_sort { crate::rpo_sort(func) } } } struct WorkItem { loc: LocId, split_bid: BlockId, old_target: BlockId, } #[cfg(test)] mod test { use std::sync::Arc; #[test] fn basic_no_split() { let (mut func, strings) = testutils::build_test_func(&[ testutils::Block::jmp_op("a", ["b", "c"]), testutils::Block::jmp("b", "d"), testutils::Block::jmp("c", "d"), testutils::Block::ret("d"), ]); let expected = func.clone(); super::split_critical_edges(&mut func, true); testutils::assert_func_struct_eq(&func, &expected, &strings); } #[test] fn basic_split() { let (mut func, strings) = testutils::build_test_func(&[ testutils::Block::jmp_op("a", ["b", "c"]), testutils::Block::jmp("b", "d"), testutils::Block::jmp_op("c", ["d", "e"]), testutils::Block::ret("d"), testutils::Block::ret("e"), ]); super::split_critical_edges(&mut func, true); let expected = testutils::build_test_func_with_strings( &[ testutils::Block::jmp_op("a", ["b", "c"]), testutils::Block::jmp("b", "d"), testutils::Block::jmp_op("c", ["f", "e"]), testutils::Block::jmp("f", "d").unnamed(), testutils::Block::ret("d"), testutils::Block::ret("e"), ], Arc::clone(&strings), ); testutils::assert_func_struct_eq(&func, &expected, &strings); } }
Rust
hhvm/hphp/hack/src/hackc/ir/passes/lib.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. #![feature(box_patterns)] pub mod r#async; pub mod clean; pub mod control; pub mod critedge; pub mod rpo_sort; pub mod ssa; pub use r#async::unasync; pub use critedge::split_critical_edges; pub use rpo_sort::rpo_sort;
Rust
hhvm/hphp/hack/src/hackc/ir/passes/rpo_sort.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use analysis::rpo::compute_rpo; use ir_core::BlockId; use ir_core::Func; use newtype::HasNone; use newtype::IdVec; /// Sort func's blocks using reverse postorder DFS, renumbering successor edges as needed. /// /// RPO has the nice property that an Instr's operands will always be "earlier" in the ordering. /// /// Note that blocks unreachable from the entry block will be discarded. pub fn rpo_sort(func: &mut Func<'_>) { let rpo = compute_rpo(func); if block_order_matches(func, &rpo) { // Already in RPO, nothing to do. return; } // Create the mapping from old BlockId to new BlockId. // Dead blocks will have a BlockId::NONE entry. let remap = order_to_remap(&rpo, func.blocks.len()); // Update successor edges for surviving blocks to use the new BlockIds. // (Note that this double loop will make it so that the closer to RPO we // start the less we have to do.) for (old, &new) in remap.iter().enumerate() { if new != BlockId::NONE { let bid = BlockId(old as u32); for edge in func.edges_mut(bid) { let target = remap[*edge]; debug_assert_ne!(target, BlockId::NONE); *edge = target; } } } for param in &mut func.params { if let Some(dv) = param.default_value.as_mut() { if let Some(target) = remap.get(dv.init) { dv.init = *target; } } } // Update catch_bids for TryCatch frames. for ex_frame in &mut func.ex_frames.values_mut() { let bid = &mut ex_frame.catch_bid; if *bid != BlockId::NONE { let target = remap[*bid]; // TODO: If target is BlockId::NONE then this ex_frame is no longer // needed and should be reaped. // debug_assert_ne!(target, BlockId::NONE); *bid = target; } } // Drop dead blocks and put the others in the RPO order specified by remap. permute_and_truncate(&mut func.blocks, remap); assert_eq!(func.blocks.len(), rpo.len()); } /// Invert the block order in order to map each old BlockId to its new BlockId. /// Dead blocks (those not listed in order) map to BlockId::NONE. fn order_to_remap(order: &[BlockId], len: usize) -> IdVec<BlockId, BlockId> { let mut remap = IdVec::new_from_vec(vec![BlockId::NONE; len]); for (i, &bid) in order.iter().enumerate() { // Check for duplicates in 'order'. debug_assert_eq!(remap[bid], BlockId::NONE); remap[bid] = BlockId(i as u32); } remap } /// Replace 'value' with a Vec where each entry is moved to the slot specified in remap. /// /// Entries that map to Id::NONE are discarded, in which case the Vec will shrink. /// /// Entries other than Id::NONE must be unique, so if there are no Id::NONE then this /// computes a permutation. pub fn permute_and_truncate<Id, T>(values: &mut IdVec<Id, T>, mut remap: IdVec<Id, Id>) where Id: HasNone + Into<usize> + From<u32> + Ord + PartialEq + Eq + Copy, { // This algorithm walks left-to-right in the values array, only moving on when // the current slot has the correct value in it. // // It works by looking at what's in the slot, and if it's not what is supposed to // be there it swaps it into where it's supposed to be and tries again with the // value it just swapped in from the later slot. So at each step we correct at least // one value, but perhaps not the one at the current slot. // // When hit a value we need to discard, rather than swapping we pop the last entry, // drop that into the current slot, and retry. This way the array shrinks. let mut slot = Id::from(0); while slot < Id::from(values.len() as u32) { // Where we want values[slot] to go. let mut desired_slot = remap[slot]; while slot != desired_slot { if desired_slot != Id::NONE { // Swap the current slot to where it belongs, thus making progress, and retry. values.swap(slot, desired_slot); std::mem::swap(&mut remap[desired_slot], &mut desired_slot); } else { // Discard this value. values.swap_remove(slot.into()); if slot.into() == values.len() { return; } desired_slot = remap[Id::from(values.len() as u32)]; } } slot = Id::from((slot.into() + 1) as u32); } } /// Are the Blocks in func already in the order specified by rpo? fn block_order_matches<'a>(func: &Func<'a>, order: &[BlockId]) -> bool { // See if the ordering is the no-op ordering [0, 1, 2, 3, blocks.len()). order.len() == func.blocks.len() && order.iter().enumerate().all(|(i, &b)| { let bid_as_usize: usize = b.into(); i == bid_as_usize }) } #[cfg(test)] mod tests { use hash::HashMap; use hash::HashSet; use ir_core::Block; use ir_core::BlockId; use rand::seq::SliceRandom; use rand::thread_rng; use rand::Rng; use super::*; fn make_dummy_blocks(names: &[&str]) -> IdVec<BlockId, Block> { IdVec::new_from_vec( names .iter() .map(|name| Block::default().with_pname(*name)) .collect(), ) } #[test] fn permute() { let mut blocks = make_dummy_blocks(&["s", "a", "c", "r", "e", "b", "l", "m"]); let order = IdVec::new_from_vec(vec![ BlockId(0), BlockId(3), BlockId(1), BlockId(2), BlockId(7), BlockId(5), BlockId(6), BlockId(4), ]); permute_and_truncate(&mut blocks, order); let q: Vec<_> = blocks .iter() .map(|b| b.pname_hint.as_ref().map_or("", String::as_str)) .collect(); assert_eq!(q.join(""), "scramble"); } #[test] fn permute_and_drop() { let mut blocks = make_dummy_blocks(&["s", "a", "c", "r", "e", "b", "l", "m"]); let order = IdVec::new_from_vec(vec![ BlockId::NONE, BlockId(2), BlockId(0), BlockId(1), BlockId::NONE, BlockId::NONE, BlockId::NONE, BlockId(3), ]); permute_and_truncate(&mut blocks, order); let q: Vec<_> = blocks .iter() .map(|b| b.pname_hint.as_ref().map_or("", String::as_str)) .collect(); assert_eq!(q.join(""), "cram"); } #[test] fn permute_random() { let names = ["a", "b", "c", "d", "e", "f"]; let blocks = make_dummy_blocks(&names); let mut rng = thread_rng(); for _ in 0..100 { // Create a random selection, including usually dropping entries. let mut order = (0..names.len()) .map(|n| BlockId(n as u32)) .collect::<Vec<_>>(); order.shuffle(&mut rng); order.truncate(rng.gen_range(0..order.len())); let mut b1 = blocks.clone(); permute_and_truncate(&mut b1, order_to_remap(&order, blocks.len())); let result: Vec<_> = b1 .iter() .map(|b| b.pname_hint.as_ref().map_or("", String::as_str)) .collect(); assert_eq!(result.len(), order.len()); for (&r, o) in result.iter().zip(order) { let i: usize = o.into(); assert_eq!(r, names[i]); } } } // Helper function for postorder DFS. fn postorder_aux<'a>( cfg: &HashMap<&'a str, Vec<&'a str>>, block: &'a str, result: &mut Vec<String>, seen: &mut HashSet<&'a str>, ) { if !seen.contains(block) { seen.insert(block); for s in cfg[block].iter().rev() { postorder_aux(cfg, s, result, seen) } result.push(format!("{}({})", block, cfg[block].join(","))); } } // Recursive reference implementation. fn rpo_reference(testcase: &[testutils::Block]) -> String { let mut cfg: HashMap<&str, Vec<&str>> = HashMap::default(); for block in testcase { cfg.insert( &block.name, block.successors().map(String::as_str).collect(), ); } let mut result = Vec::with_capacity(cfg.len()); let mut seen: HashSet<&str> = HashSet::with_capacity_and_hasher(cfg.len(), Default::default()); postorder_aux(&cfg, &testcase[0].name, &mut result, &mut seen); result.reverse(); result.join(",") } #[test] fn rpo() { // Define a little CFG with a some branches and loops. let blocks: Vec<testutils::Block> = vec![ testutils::Block::jmp("a", "b"), testutils::Block::jmp_op("b", ["c", "d"]), testutils::Block::jmp("c", "e"), testutils::Block::jmp_op("d", ["e", "f"]), testutils::Block::jmp_op("e", ["f", "f"]), testutils::Block::jmp_op("f", ["b", "g"]), testutils::Block::ret("g"), testutils::Block::jmp_op("dead", ["b", "dead2"]), testutils::Block::jmp("dead2", "dead"), ]; let mut rng = thread_rng(); for _ in 0..50 { // Shuffle block order, but leave the entry block first. We should always // end up with the same RPO, since that depends only on the CFG. let mut c = blocks.clone(); c[1..].shuffle(&mut rng); let (mut func, _) = testutils::build_test_func(&c); rpo_sort(&mut func); let order = func .blocks .iter() .map(|b| b.pname_hint.as_ref().map_or("", String::as_str)) .collect::<Vec<_>>() .join(","); assert_eq!(order, "a,b,c,d,e,f,g"); } } #[test] fn random_rpo() { let names = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]; let mut rng = thread_rng(); for _ in 0..500 { // Build up a random function. let num_blocks = rng.gen_range(2..names.len()); let mut blocks = Vec::new(); let mut rblocks = Vec::new(); for i in 0..num_blocks { // Choose 0, 1 or 2 successor, with only a small chance of 0. let num_successors = (rng.gen_range(0..7) + 2) / 3; let mut succ = || { // NOTE: You can't branch to the entry block. names[rng.gen_range(1..num_blocks)] }; let (term, rterm) = match num_successors { 0 => (testutils::Terminator::Ret, testutils::Terminator::Ret), 1 => { let a = succ(); ( testutils::Terminator::Jmp(a.to_string()), testutils::Terminator::Jmp(a.to_string()), ) } 2 => { let a = succ(); let b = succ(); ( testutils::Terminator::JmpOp(a.to_string(), b.to_string()), testutils::Terminator::JmpOp(b.to_string(), a.to_string()), ) } _ => unreachable!(), }; blocks.push(testutils::Block::ret(names[i]).with_terminator(term)); rblocks.push(testutils::Block::ret(names[i]).with_terminator(rterm)); } let (mut func, _) = testutils::build_test_func(&blocks); rpo_sort(&mut func); let (mut rfunc, _) = testutils::build_test_func(&rblocks); rpo_sort(&mut rfunc); fn bname<'a>(func: &'a Func<'_>, bid: BlockId) -> &'a str { func.blocks[bid] .pname_hint .as_ref() .map_or("", String::as_str) } let actual = func .blocks .iter() .enumerate() .map(|(i, b)| { let succ = func .edges(BlockId(i as u32)) .iter() .map(|e| bname(&func, *e)) .collect::<Vec<_>>() .join(","); format!( "{}({})", b.pname_hint.as_ref().map_or("", String::as_str), succ ) }) .collect::<Vec<_>>() .join(","); let ractual = analysis::compute_rrpo(&rfunc) .iter() .map(|b| { let succ = rfunc .edges(*b) .iter() .rev() .map(|e| bname(&rfunc, *e)) .collect::<Vec<_>>() .join(","); format!("{}({})", bname(&rfunc, *b), succ) }) .collect::<Vec<_>>() .join(","); // Compare its RPO to a simple reference implementation's. let expected = rpo_reference(&blocks); assert_eq!(actual, expected); assert_eq!(ractual, expected); } } }
Rust
hhvm/hphp/hack/src/hackc/ir/passes/ssa.rs
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. use std::collections::hash_map::Entry; use analysis::compute_predecessor_blocks; use analysis::PredecessorCatchMode; use analysis::PredecessorFlags; use analysis::Predecessors; use ir_core::func_builder::TransformInstr; use ir_core::func_builder::TransformState; use ir_core::instr::Special; use ir_core::instr::Terminator; use ir_core::instr::Tmp; use ir_core::newtype::VarIdMap; use ir_core::BlockId; use ir_core::Func; use ir_core::FuncBuilder; use ir_core::Instr; use ir_core::InstrId; use ir_core::StringInterner; use ir_core::ValueId; use ir_core::VarId; use itertools::Itertools; use newtype::IdVec; /* This pass converts a Func to SSA form by eliminating GetVar and SetVar instrs. It uses an algorithm much like that described in "Simple and Efficient Construction of Static Single Assignment Form", https://pp.info.uni-karlsruhe.de/uploads/publikationen/braun13cc.pdf The high-level idea is pretty simple: replace each GetVar with the value most recently assigned by a SetVar, if known. If not, as in a variable conditionally assigned inside an "if", then create a Param in the GetVar's block and replace all uses of the GetVar with it. Every predecessor block is then required to pass in its "ending" value for that variable, which may recursively force that predecessor to get the value from its predecessors and so on. All block iteration is done using reverse postorder DFS, which is how blocks are stored in every Func. Detailed steps: 1) For each block, compute "local" dataflow facts using a simple forward scan: a) Identify variables assigned in that block, and the final value assigned to each one ("exit_value"). b) Identify variables read before being written in that block, recording them in the keys of "entry_value"). These are "live on entry". 2) Propagate dataflow information globally through the CFG: If a variable is live on entry to a block, then it is also live on entry to every predecessor block that does not assign to that variable, and so on recursively. Update each block's entry_value keys appropriately. 3) Fill in each block's "entry_value" table with the incoming values of all live variables. The entry_value for each live variable depends on its exit_value in all predecessor blocks: a) If all predecessor blocks have the same known exit_value for that variable, then that is also the entry_value. b) If predecessor blocks disagree about the exit_value, or one of them hasn't computed that variable's exit_value yet (due to a loop), then create a Param and use that as the entry_value. c) Now that entry_value is complete, update exit_value. For each variable in entry_value: i) If it was assigned by that block, meaning it's already got an entry in exit_value, do nothing. The entry_value is overridden by the local assignment. ii) Else update that variable's exit_value to be its entry_value (the variable is just "passing through" the block without being touched). Note that this step can create unnecessary Params (those whose possible values consist only of a single non-Param value and possibly themselves). For example, each variable defined outside loops and accessed within them will pessimistically get a Param at the loop head, even if it is never assigned to inside the loop. We could of course clean up unnecessary Params here, but for code simplicity we will instead delegate that work to a separate Param optimization pass which we need anyway (e.g. other optimizations like DCE can make Params unnecessary long after SSA formation is complete). 4) Rewrite the function. The tables computed above give us enough information to rewrite the Func to eliminate GetVar and SetVar. For each block: a) Append any new Params to the block's params vec. b) For each instr in the block: - if SetVar, update entry_value with the assigned value. entry_value is now misleadingly named, but it's safe to clobber now. Discard the SetVar. - if GetVar, replace it with the current value in entry_value - If target has new Params, it must have multiple predecessors. We know the block branching to it must end with Br or ArgBr because there are no critical edges in the CFG. Convert it to a ArgBr and append the expanded list of arguments based on exit_value (which should be equivalent to entry_value). */ /// Extra per-block data needed by MakeSSA. #[derive(Default)] struct BlockInfo { // The value of each live local block entry. entry_value: VarIdMap<ValueId>, // The value of each live local block exit. exit_value: VarIdMap<ValueId>, // Extra block Params this block needs. extra_params: Vec<( VarId, // Declare InstrId, // Param )>, } /// Tracks values assigned to this variable. /// If only one value is ever assigned, we don't need to make Params for it. #[derive(Copy, Clone)] enum SetValue { One(ValueId), Multiple, } #[derive(Copy, Clone)] struct Decl { /// If we need extra per-variable info like types this is the place to store /// it. set_value: SetValue, } struct MakeSSA<'a> { predecessors: Predecessors, block_info: IdVec<BlockId, BlockInfo>, // Values from Local::Declare we have seen. decls: VarIdMap<Decl>, strings: &'a StringInterner, } impl<'a> MakeSSA<'a> { fn new(func: &Func<'_>, strings: &'a StringInterner) -> MakeSSA<'a> { let predecessors = compute_predecessor_blocks( func, PredecessorFlags { catch: PredecessorCatchMode::Throw, ..Default::default() }, ); let block_info: IdVec<BlockId, BlockInfo> = (0..func.blocks.len()).map(|_| Default::default()).collect(); MakeSSA { predecessors, block_info, decls: Default::default(), strings, } } fn run(&mut self, func: &mut Func<'_>) { self.analyze_dataflow(func); self.create_params(func); self.rewrite_instrs(func); } // Steps (1) and (2). fn analyze_dataflow(&mut self, func: &Func<'_>) { // Stack of dataflow information to propagate, in lieu of recursion. // BlockId needs the value of Declare's InstrId on entry because // Get wants it (directly or indirectly). let mut dataflow_stack: Vec<(BlockId, InstrId, VarId)> = Vec::new(); // First analyze each block locally to see what it reads and writes. for bid in func.block_ids() { let info = &mut self.block_info[bid]; for &iid in &func.blocks[bid].iids { match func.instrs[iid] { Instr::Special(Special::Tmp(Tmp::GetVar(var))) => { note_live(&mut dataflow_stack, info, bid, iid, var) } Instr::Special(Special::Tmp(Tmp::SetVar(var, value))) => { info.exit_value.insert(var, value); // See which values are ever assigned to this variable. match self.decls.entry(var) { Entry::Vacant(e) => { // First assignment we've ever seen to this variable. e.insert(Decl { set_value: SetValue::One(value), }); } Entry::Occupied(mut e) => { let decl = e.get_mut(); match decl.set_value { SetValue::One(old_iid) if old_iid != value => { // Two distinct InstrId are assigned to this variable, // so we may need Params later. decl.set_value = SetValue::Multiple; } SetValue::Multiple | SetValue::One(_) => {} } } } } _ => {} } } } // Propagate local variable liveness around the CFG. while let Some((bid, get_local_iid, var)) = dataflow_stack.pop() { if bid == Func::ENTRY_BID { // Uh oh, the entry block needs the value of a local variable on // entry. That must mean it's used uninitialized by // get_local_iid. panic!( "Local variable may be used uninitialized by '{}' in\n{}", print::FmtInstr(func, self.strings, get_local_iid), print::DisplayFunc::new(func, true, self.strings), ); }; for &pred_bid in &self.predecessors[&bid] { note_live( &mut dataflow_stack, &mut self.block_info[pred_bid], pred_bid, get_local_iid, var, ); } } } // Step (3). fn create_params(&mut self, func: &mut Func<'_>) { // Guarantee each var live at block entry has a value we can use. // // In loops this will sometimes create degenerate Params, which // are always passed the same value or themselves. We clean those up // elsewhere rather than trying to get too clever here. for bid in func.block_ids() { let pred_bids = &self.predecessors[&bid]; // Sort to make param creation order deterministic. Also, we need // a snapshot of this map anyway since we are going to mutate it. let mut entry_values = self.block_info[bid] .entry_value .keys() .copied() .collect_vec(); entry_values.sort_unstable(); for var in entry_values { // Optimize the trivial case where we know every predecessor // passes the same value. This won't help for loop headers // because we haven't processed the predecessors yet, but it // catches easier cases. let mut value = ValueId::none(); let decl = &self.decls[&var]; match decl.set_value { SetValue::One(v) => { // Only one value is ever assigned to this // local. There's no need to examine dataflow at all, we // don't need a Param. value = v; } SetValue::Multiple => { for &p in pred_bids { match self.block_info[p].exit_value.get(&var) { Some(pred_value) => { if value.is_none() { // This is the first value we've seen; // compare to the rest. value = *pred_value } else if value != *pred_value { // Getting two different values passed // in, make a Param. value = ValueId::none(); break; } } None => { if p != bid { // Predecessor doesn't know var's value // yet, so give up. But we can ignore // the case where a block branches to // itself without reassigning the // variable, because that has no effect // on whether the input value is fixed. value = ValueId::none(); break; } } } } } } let info = &mut self.block_info[bid]; if value.is_none() { // We aren't sure what the value is. So make a Param. let iid = func.alloc_instr(Instr::param()); value = ValueId::from_instr(iid); info.extra_params.push((var, iid)); }; info.entry_value.insert(var, value); // If we already have an exit_value, meaning the variable is // assigned in this block, don't override it. But if not, the // exit_value is the entry_value. info.exit_value.entry(var).or_insert(value); } } } // Step (4). fn rewrite_instrs(&mut self, func: &mut Func<'_>) { FuncBuilder::borrow_func_no_strings(func, |rw| { for bid in rw.func.block_ids() { let info = &mut self.block_info[bid]; // Record any additional Params. if !info.extra_params.is_empty() { let bparams = &mut rw.func.blocks[bid].params; for (_, param) in &info.extra_params { bparams.push(*param); } bparams.shrink_to_fit(); } // Walk the block and process Local instrs. rw.rewrite_block(bid, self); } }); } } impl<'a> TransformInstr for MakeSSA<'a> { fn apply( &mut self, _iid: InstrId, i: Instr, rw: &mut FuncBuilder<'_>, _state: &mut TransformState, ) -> Instr { let bid = rw.cur_bid(); match i { Instr::Terminator(Terminator::Jmp(..) | Terminator::JmpArgs(..)) => { // Pass args for new Params, if any, to the target block. let (target, args, loc): (_, &[ValueId], _) = match i { Instr::Terminator(Terminator::JmpArgs(target, ref args, loc)) => { (target, args, loc) } Instr::Terminator( Terminator::Enter(target, loc) | Terminator::Jmp(target, loc), ) => (target, &[], loc), _ => unreachable!(), }; let target_info = &self.block_info[target]; if target_info.extra_params.is_empty() { i } else { let mut args = args.to_vec(); for (var, _) in &target_info.extra_params { let value = rw.find_replacement(self.block_info[bid].entry_value[var]); args.push(value); } assert!(!args.is_empty()); let t = Terminator::JmpArgs(target, args.into(), loc); Instr::Terminator(t) } } Instr::Special(Special::Tmp(Tmp::SetVar(var, value))) => { self.block_info[bid].entry_value.insert(var, value); Instr::tombstone() } Instr::Special(Special::Tmp(Tmp::GetVar(var))) => { let value = self.block_info[bid].entry_value[&var]; Instr::copy(value) } i => i, } } } /// Record that the variable in var is used in block 'bid'. We track /// which instr uses it (get_local_iid), rather than just the fact that /// the var is used, only for error reporting purposes. fn note_live( dataflow_stack: &mut Vec<(BlockId, InstrId, VarId)>, info: &mut BlockInfo, bid: BlockId, get_local_iid: InstrId, var: VarId, ) { // NOTE: We temporarily stash get_local_iid in this table, to report // errors, but later we will replace it with the actual value. if !info.exit_value.contains_key(&var) && info .entry_value .insert(var, ValueId::from_instr(get_local_iid)) .is_none() { // Recursively propagate liveness to all predecessors. dataflow_stack.push((bid, get_local_iid, var)) } } pub(crate) fn is_ssa(func: &Func<'_>) -> bool { !func .body_instrs() .any(|i| matches!(i, Instr::Special(Special::Tmp(..)))) } pub fn run(func: &mut Func<'_>, strings: &StringInterner) -> bool { if is_ssa(func) { false } else { let mut pass = MakeSSA::new(func, strings); pass.run(func); true } } #[cfg(test)] mod test { use std::sync::Arc; use ir_core::instr::HasOperands; use ir_core::instr::Predicate; use ir_core::instr::Terminator; use ir_core::Constant; use ir_core::FuncBuilder; use ir_core::FunctionId; use ir_core::LocId; use ir_core::StringInterner; use super::*; #[test] fn already_ssa() { let loc = LocId::NONE; let strings = Arc::new(StringInterner::default()); let mut func = FuncBuilder::build_func(Arc::clone(&strings), |builder| { // %0 = call("my_fn", [42]) // %1 = ret null let value = builder.emit_constant(Constant::Int(42)); let null = builder.emit_constant(Constant::Null); let id = FunctionId::from_str("my_fn", &strings); builder.emit(Instr::simple_call(id, &[value], loc)); builder.emit(Instr::ret(null, loc)); }); verify::verify_func(&func, &Default::default(), &strings); assert!(is_ssa(&func)); let res = run(&mut func, &strings); assert!(!res); } #[test] fn basic() { let loc = LocId::NONE; let strings = Arc::new(StringInterner::default()); let mut func = FuncBuilder::build_func(Arc::clone(&strings), |builder| { // %0 = declare // %1 = set(%0, 42) // %2 = get(%0) // call("my_fn", [%2]) // ret null let var = VarId::from_usize(0); let value = builder.emit_constant(Constant::Int(42)); builder.emit(Instr::set_var(var, value)); let null = builder.emit_constant(Constant::Null); let value = builder.emit(Instr::get_var(var)); let id = FunctionId::from_str("my_fn", &strings); builder.emit(Instr::simple_call(id, &[value], loc)); builder.emit(Instr::ret(null, loc)); }); verify::verify_func(&func, &Default::default(), &strings); assert!(!is_ssa(&func)); let res = run(&mut func, &strings); assert!(res); assert_eq!(func.blocks.len(), 1); let mut it = func.body_instrs(); let instr = it.next(); assert!(matches!(instr, Some(Instr::Call(..)))); let ops = instr.unwrap().operands(); assert_eq!(ops.len(), 1); assert!(matches!( ops[0].constant().map(|lit| func.constant(lit)), Some(Constant::Int(42)) )); assert!(matches!( it.next(), Some(Instr::Terminator(Terminator::Ret(..))) )); assert!(matches!(it.next(), None)); } #[test] fn diamond() { let loc = LocId::NONE; let strings = Arc::new(StringInterner::default()); let mut func = FuncBuilder::build_func(Arc::clone(&strings), |builder| { // %0 = declare // %1 = declare // %2 = declare // set(%0, 42) // set(%1, 314) // if true jmp b1 else b2 // b1: // set(%1, 123) // set(%2, 1) // jmp b3 // b2: // set(%2, 2) // jmp b3 // b3: // %3 = get(%0) // %4 = get(%1) // %4 = get(%2) // call("my_fn", [%3, %4, %5]) // ret null let var0 = VarId::from_usize(0); let var1 = VarId::from_usize(1); let var2 = VarId::from_usize(2); let value = builder.emit_constant(Constant::Int(42)); builder.emit(Instr::set_var(var0, value)); let value = builder.emit_constant(Constant::Int(314)); builder.emit(Instr::set_var(var1, value)); let true_bid = builder.alloc_bid(); let false_bid = builder.alloc_bid(); let join_bid = builder.alloc_bid(); let value = builder.emit_constant(Constant::Bool(true)); builder.emit(Instr::jmp_op( value, Predicate::NonZero, true_bid, false_bid, loc, )); builder.start_block(true_bid); let value = builder.emit_constant(Constant::Int(123)); builder.emit(Instr::set_var(var1, value)); let value = builder.emit_constant(Constant::Int(1)); builder.emit(Instr::set_var(var2, value)); builder.emit(Instr::jmp(join_bid, loc)); builder.start_block(false_bid); let value = builder.emit_constant(Constant::Int(2)); builder.emit(Instr::set_var(var2, value)); builder.emit(Instr::jmp(join_bid, loc)); builder.start_block(join_bid); let null = builder.emit_constant(Constant::Null); let value0 = builder.emit(Instr::get_var(var0)); let value1 = builder.emit(Instr::get_var(var1)); let value2 = builder.emit(Instr::get_var(var2)); let id = FunctionId::from_str("my_fn", &strings); builder.emit(Instr::simple_call(id, &[value0, value1, value2], loc)); builder.emit(Instr::ret(null, loc)); }); verify::verify_func(&func, &Default::default(), &strings); assert!(!is_ssa(&func)); let res = run(&mut func, &strings); assert!(res); crate::clean::run(&mut func); // b0: // %0 = jmp if nonzero #2 to b1 else b2 // b1: // %1 = jmp to b3 with (#3, #4) // b2: // %2 = jmp to b3 with (#1, #5) // b3(%3, %4): // %5 = call direct "my_fn"(#0, %3, %4) num_rets(0) NONE // %6 = ret #6 let mut it = func.body_instrs(); assert!(match it.next() { Some(Instr::Terminator(Terminator::JmpOp { targets: [true_bid, false_bid], .. })) if true_bid.as_usize() == 1 && false_bid.as_usize() == 2 => true, _ => false, }); assert!(match it.next() { Some(Instr::Terminator(Terminator::JmpArgs(bid, values, _))) if bid.as_usize() == 3 && values.len() == 2 => true, _ => false, }); assert!(match it.next() { Some(Instr::Terminator(Terminator::JmpArgs(bid, values, _))) if bid.as_usize() == 3 && values.len() == 2 => true, _ => false, }); assert!(match it.next() { Some(i @ Instr::Call(..)) if i.operands().len() == 3 => true, _ => false, }); assert!(matches!( it.next(), Some(Instr::Terminator(Terminator::Ret(..))) )); assert!(matches!(it.next(), None)); } }
TOML
hhvm/hphp/hack/src/hackc/ir/print/Cargo.toml
# @generated by autocargo [package] name = "print" version = "0.0.0" edition = "2021" [lib] path = "lib.rs" [dependencies] ffi = { version = "0.0.0", path = "../../../utils/ffi" } ir_core = { version = "0.0.0", path = "../ir_core" }
Rust
hhvm/hphp/hack/src/hackc/ir/print/formatters.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. //! Formatting Functions //! //! These functions are used to print the IR in a pseudo-assembly format. //! //! The functions in this file (as opposed to print.rs) print partial lines of //! IR. As a result they mostly will be in the form: //! ``` //! struct FmtThing { .. } //! impl Display for FmtThing { .. } //! ``` //! use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Result; use ffi::Str; use ir_core::instr::HasLoc; use ir_core::instr::Special; use ir_core::BareThisOp; use ir_core::CollectionType; use ir_core::IncDecOp; use ir_core::InitPropOp; use ir_core::IsTypeOp; use ir_core::MOpMode; use ir_core::ReadonlyOp; use ir_core::SetOpOp; use ir_core::SpecialClsRef; use ir_core::SrcLoc; use ir_core::StringInterner; use ir_core::*; use crate::print::FuncContext; use crate::util::FmtEscapedString; use crate::util::FmtSep; pub(crate) fn get_bit<T>(attr: &mut T, bit: T, s: &'static str) -> Option<&'static str> where T: Copy + std::ops::BitAnd<T, Output = T> + std::ops::SubAssign + std::ops::BitAndAssign<T> + PartialEq<T>, { if *attr & bit == bit { *attr -= bit; Some(s) } else { None } } pub(crate) fn flag_get_bit<T>( flag: bool, attr: &mut T, bit: T, s: &'static str, ) -> Option<&'static str> where T: Copy + std::ops::BitAnd<T, Output = T> + std::ops::SubAssign + std::ops::BitAndAssign<T> + PartialEq<T>, { if !flag { None } else if *attr & bit == bit { *attr -= bit; Some(s) } else { None } } #[derive(Copy, Clone, Eq, PartialEq)] pub(crate) enum AttrContext { Class, Constant, Function, Method, Property, Typedef, } pub(crate) struct FmtAttr(pub Attr, pub AttrContext); impl Display for FmtAttr { fn fmt(&self, w: &mut Formatter<'_>) -> Result { let FmtAttr(mut attr, ctx) = *self; let is_class = ctx == AttrContext::Class; let is_func = ctx == AttrContext::Function; #[rustfmt::skip] FmtSep::new( "[", ", ", "]", [ get_bit(&mut attr, Attr::AttrAbstract, "abstract"), get_bit(&mut attr, Attr::AttrBuiltin, "builtin"), get_bit(&mut attr, Attr::AttrDeepInit, "deep_init"), get_bit(&mut attr, Attr::AttrDynamicallyCallable, "dynamically_callable"), get_bit(&mut attr, Attr::AttrEnumClass, "enum_class"), get_bit(&mut attr, Attr::AttrFinal, "final"), get_bit(&mut attr, Attr::AttrForbidDynamicProps, "no_dynamic_props"), get_bit(&mut attr, Attr::AttrInitialSatisfiesTC, "initial_satisfies_tc"), get_bit(&mut attr, Attr::AttrInterceptable, "interceptable"), get_bit(&mut attr, Attr::AttrInterface, "interface"), get_bit(&mut attr, Attr::AttrInternal, "internal"), flag_get_bit(is_class, &mut attr, Attr::AttrIsClosureClass, "is_closure_class"), get_bit(&mut attr, Attr::AttrIsConst, "const"), flag_get_bit(is_func, &mut attr, Attr::AttrIsMethCaller, "is_meth_caller"), get_bit(&mut attr, Attr::AttrIsReadonly, "readonly"), get_bit(&mut attr, Attr::AttrLSB, "lsb"), get_bit(&mut attr, Attr::AttrLateInit, "late_init"), get_bit(&mut attr, Attr::AttrNoBadRedeclare, "no_bad_redeclare"), get_bit(&mut attr, Attr::AttrNoImplicitNullable, "no_implicit_null"), get_bit(&mut attr, Attr::AttrNoInjection, "no_injection"), get_bit(&mut attr, Attr::AttrNoOverride, "no_override"), get_bit(&mut attr, Attr::AttrNoReifiedInit, "no_reified_init"), get_bit(&mut attr, Attr::AttrPersistent, "persistent"), get_bit(&mut attr, Attr::AttrPrivate, "private"), get_bit(&mut attr, Attr::AttrProtected, "protected"), get_bit(&mut attr, Attr::AttrProvenanceSkipFrame, "provenance_skip_frame"), get_bit(&mut attr, Attr::AttrPublic, "public"), get_bit(&mut attr, Attr::AttrReadonlyReturn, "readonly_return"), get_bit(&mut attr, Attr::AttrSealed, "sealed"), get_bit(&mut attr, Attr::AttrStatic, "static"), get_bit(&mut attr, Attr::AttrSystemInitialValue, "system_initial_value"), get_bit(&mut attr, Attr::AttrTrait, "trait"), get_bit(&mut attr, Attr::AttrVariadicParam, "variadic_param"), ] .into_iter() .flatten(), |w, s| w.write_str(s), ) .fmt(w)?; assert!(attr.is_empty(), "Unprocessed attr: {attr:?}"); Ok(()) } } pub(crate) struct FmtAttribute<'a>(pub &'a Attribute, pub &'a StringInterner); impl Display for FmtAttribute<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let FmtAttribute(attr, strings) = *self; FmtIdentifierId(attr.name.id, strings).fmt(f)?; if !attr.arguments.is_empty() { write!( f, "({})", FmtSep::comma(attr.arguments.iter(), |w, tv| { FmtTypedValue(tv, strings).fmt(w) }) )?; } Ok(()) } } pub(crate) struct FmtBareThisOp(pub BareThisOp); impl Display for FmtBareThisOp { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let s = match self.0 { BareThisOp::Notice => "notice", BareThisOp::NoNotice => "no_notice", BareThisOp::NeverNull => "never_null", _ => panic!("bad BareThisOp value"), }; f.write_str(s) } } pub struct FmtBid<'a>(pub &'a Func<'a>, pub BlockId, /* verbose */ pub bool); impl Display for FmtBid<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let FmtBid(body, bid, verbose) = *self; if let Some(block) = body.get_block(bid) { let pname = block.pname_hint.as_ref(); if !verbose { if let Some(pname) = pname { return write!(f, "b{}[\"{}\"]", bid.as_usize(), pname); } } } FmtRawBid(bid).fmt(f) } } pub(crate) struct FmtCollectionType(pub(crate) CollectionType); impl Display for FmtCollectionType { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let kind = match self.0 { CollectionType::Vector => "vector", CollectionType::Map => "map", CollectionType::Set => "set", CollectionType::Pair => "pair", CollectionType::ImmVector => "imm_vector", CollectionType::ImmMap => "imm_map", CollectionType::ImmSet => "imm_set", _ => panic!("bad CollectionType value"), }; f.write_str(kind) } } pub(crate) struct FmtSetOpOp(pub SetOpOp); impl FmtSetOpOp { pub(crate) fn as_str(&self) -> &'static str { match self.0 { SetOpOp::AndEqual => "&=", SetOpOp::ConcatEqual => ".=", SetOpOp::DivEqual => "/=", SetOpOp::MinusEqual => "-=", SetOpOp::ModEqual => "%=", SetOpOp::MulEqual => "*=", SetOpOp::OrEqual => "|=", SetOpOp::PlusEqual => "+=", SetOpOp::PowEqual => "**=", SetOpOp::SlEqual => "<<=", SetOpOp::SrEqual => ">>=", SetOpOp::XorEqual => "^=", _ => panic!("invalid SetOpOp value"), } } } impl Display for FmtSetOpOp { fn fmt(&self, w: &mut Formatter<'_>) -> Result { w.write_str(self.as_str()) } } struct FmtFloat(f64); impl Display for FmtFloat { fn fmt(&self, f: &mut Formatter<'_>) -> Result { use std::num::FpCategory; let value = self.0; let s = match value.classify() { FpCategory::Nan => "nan", FpCategory::Infinite if value.is_sign_negative() => "-inf", FpCategory::Infinite => "inf", FpCategory::Zero if value.is_sign_negative() => "-0.0", FpCategory::Zero => "0.0", FpCategory::Subnormal | FpCategory::Normal => { let mut s = format!("{}", value); if !s.contains('.') { s.push_str(".0"); } return f.write_str(&s); } }; f.write_str(s) } } pub(crate) struct FmtFuncParams<'a>(pub &'a Func<'a>, pub &'a StringInterner); impl Display for FmtFuncParams<'_> { fn fmt(&self, w: &mut Formatter<'_>) -> Result { let FmtFuncParams(func, strings) = *self; write!( w, "({})", FmtSep::comma(&func.params, |w, param| crate::print::print_param( w, strings, func, param )) ) } } pub(crate) struct FmtIdentifier<'a>(pub(crate) &'a [u8]); impl Display for FmtIdentifier<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let FmtIdentifier(id) = *self; // Ideally we print identifiers as non-quoted strings - but if they // contain "strange" characters then we need to quote and escape them. // // Note that we don't need quotes when an identifier contains '\' // because that's not a "strange" character - we don't unescape unquoted // identifiers. // // We need to quote an empty string so it doesn't disappear. // Or if it contains non-ascii printable chars. // Or ':' (to disambiguate "Foo::Bar" from "Foo"::"Bar"). // Or if it starts with a non-letter, number, backslash. let needs_quote = id.first().map_or(true, |&c| { !(c.is_ascii_alphabetic() || c == b'_' || c == b'\\' || c == b'$') }) || id[1..] .iter() .any(|&c| !c.is_ascii_graphic() || c == b':' || c == b'#'); if !needs_quote { if let Ok(string) = std::str::from_utf8(id) { return f.write_str(string); } } FmtEscapedString(id).fmt(f) } } pub(crate) struct FmtIdentifierId<'a>(pub UnitBytesId, pub &'a StringInterner); impl Display for FmtIdentifierId<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let FmtIdentifierId(id, strings) = *self; let id = strings.lookup_bytes(id); FmtIdentifier(&id).fmt(f) } } pub(crate) struct FmtConstant<'a, 'b>(pub(crate) &'b Constant<'a>, pub &'b StringInterner); impl Display for FmtConstant<'_, '_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let FmtConstant(constant, strings) = self; match constant { Constant::Array(tv) => write!(f, "array({})", FmtTypedValue(tv, strings)), Constant::Bool(b) => write!(f, "{b}"), Constant::Dir => write!(f, "dir"), Constant::Float(value) => FmtFloat(value.to_f64()).fmt(f), Constant::File => write!(f, "file"), Constant::FuncCred => write!(f, "func_cred"), Constant::Int(value) => write!(f, "{}", value), Constant::Method => write!(f, "method"), Constant::Named(name) => write!(f, "constant({})", FmtIdentifier(name.as_bytes())), Constant::NewCol(k) => write!(f, "new_col({:?})", k), Constant::Null => write!(f, "null"), Constant::String(value) => FmtQuotedStringId(*value, strings).fmt(f), Constant::Uninit => write!(f, "uninit"), } } } pub struct FmtVid<'a>( pub &'a Func<'a>, pub ValueId, /* verbose */ pub bool, pub &'a StringInterner, ); impl Display for FmtVid<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let FmtVid(body, vid, verbose, strings) = *self; match vid.full() { FullInstrId::Constant(cid) => { if verbose { FmtRawVid(vid).fmt(f) } else { FmtConstantId(body, cid, strings).fmt(f) } } FullInstrId::Instr(iid) => { if let Some(instr) = body.get_instr(iid) { if matches!(instr, Instr::Special(Special::Tombstone)) { write!(f, "tombstone(%{})", iid.as_usize()) } else { write!(f, "%{}", iid.as_usize()) } } else if iid == InstrId::NONE { write!(f, "%none") } else { write!(f, "unknown(%{})", iid.as_usize()) } } FullInstrId::None => f.write_str("none"), } } } pub(crate) struct FmtDocComment<'a>(pub Option<&'a Str<'a>>); impl Display for FmtDocComment<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { if let Some(doc) = self.0 { FmtEscapedString(doc).fmt(f) } else { f.write_str("N") } } } pub(crate) struct FmtIncDecOp(pub IncDecOp); impl FmtIncDecOp { pub(crate) fn as_str(&self) -> &'static str { match self.0 { IncDecOp::PreInc => "pre_inc", IncDecOp::PostInc => "post_inc", IncDecOp::PreDec => "pre_dec", IncDecOp::PostDec => "post_dec", _ => panic!("bad IncDecOp value"), } } } impl Display for FmtIncDecOp { fn fmt(&self, f: &mut Formatter<'_>) -> Result { f.write_str(self.as_str()) } } pub(crate) struct FmtInitPropOp(pub InitPropOp); impl Display for FmtInitPropOp { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let s = match self.0 { InitPropOp::Static => "static", InitPropOp::NonStatic => "non_static", _ => panic!("bad InitPropOp value"), }; f.write_str(s) } } pub struct FmtInstr<'a, 'b>(pub &'b Func<'a>, pub &'b StringInterner, pub InstrId); impl Display for FmtInstr<'_, '_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let FmtInstr(func, strings, iid) = self; let instr = func.get_instr(*iid).unwrap(); let mut ctx = FuncContext { cur_loc_id: instr.loc_id(), live_instrs: Default::default(), strings, verbose: true, }; crate::print::print_instr(f, &mut ctx, func, *iid, instr)?; Ok(()) } } pub(crate) struct FmtIsTypeOp(pub IsTypeOp); impl Display for FmtIsTypeOp { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let s = match self.0 { IsTypeOp::Null => "null", IsTypeOp::Bool => "bool", IsTypeOp::Int => "int", IsTypeOp::Dbl => "double", IsTypeOp::Str => "string", IsTypeOp::Obj => "object", IsTypeOp::Res => "resource", IsTypeOp::Scalar => "scalar", IsTypeOp::Keyset => "keyset", IsTypeOp::Dict => "dict", IsTypeOp::Vec => "vec", IsTypeOp::ArrLike => "array", IsTypeOp::ClsMeth => "clsmeth", IsTypeOp::Func => "func", IsTypeOp::LegacyArrLike => "legacy_array", IsTypeOp::Class => "class", _ => panic!("bad IsTypeOp value"), }; f.write_str(s) } } pub struct FmtLid<'a>(pub LocalId, pub &'a StringInterner); impl Display for FmtLid<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let FmtLid(ref lid, strings) = *self; match *lid { LocalId::Unnamed(id) => write!(f, "@{}", id.as_usize()), LocalId::Named(var) => FmtIdentifierId(var, strings).fmt(f), } } } pub(crate) struct FmtLids<'a>(pub(crate) &'a [LocalId], pub &'a StringInterner); impl Display for FmtLids<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let FmtLids(slice, strings) = *self; write!( f, "[{}]", FmtSep::comma(slice.iter(), |f, v| { FmtLid(*v, strings).fmt(f) }) ) } } pub(crate) struct FmtConstantId<'a>( pub(crate) &'a Func<'a>, pub(crate) ConstantId, pub(crate) &'a StringInterner, ); impl Display for FmtConstantId<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let FmtConstantId(body, cid, strings) = *self; let constant = body.constant(cid); FmtConstant(constant, strings).fmt(f) } } pub struct FmtLoc<'a>(pub &'a SrcLoc); impl Display for FmtLoc<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { write!( f, "{}:{},{}:{}", self.0.line_begin, self.0.col_begin, self.0.line_end, self.0.col_end )?; Ok(()) } } pub struct FmtFullLoc<'a>(pub &'a SrcLoc, pub &'a StringInterner); impl Display for FmtFullLoc<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let FmtFullLoc(loc, strings) = self; FmtLoc(loc).fmt(f)?; if loc.filename != Filename::NONE { write!(f, " {}", FmtQuotedStringId(loc.filename.0, strings))?; } Ok(()) } } pub struct FmtLocId<'a>(pub &'a Func<'a>, pub LocId); impl Display for FmtLocId<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let FmtLocId(func, loc_id) = *self; if let Some(loc) = func.locs.get(loc_id) { FmtLoc(loc).fmt(f) } else { write!(f, "<unknown loc #{loc_id}>") } } } pub(crate) struct FmtMOpMode(pub MOpMode); impl Display for FmtMOpMode { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let s = match self.0 { MOpMode::None => "", MOpMode::Warn => "warn", MOpMode::Define => "define", MOpMode::Unset => "unset", MOpMode::InOut => "inout", _ => panic!("bad MopMode value"), }; f.write_str(s) } } pub(crate) struct FmtOptKeyValue<'a>(pub Option<LocalId>, pub LocalId, pub &'a StringInterner); impl Display for FmtOptKeyValue<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let FmtOptKeyValue(key, value, strings) = *self; match key { Some(key) => write!(f, "{} => {}", FmtLid(key, strings), FmtLid(value, strings)), None => write!(f, "{}", FmtLid(value, strings)), } } } pub(crate) struct FmtQuotedStr<'a>(pub(crate) &'a Str<'a>); impl Display for FmtQuotedStr<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { FmtEscapedString(self.0.as_ref()).fmt(f) } } pub(crate) struct FmtQuotedStringId<'a>(pub(crate) UnitBytesId, pub(crate) &'a StringInterner); impl Display for FmtQuotedStringId<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let FmtQuotedStringId(id, strings) = *self; if id == UnitBytesId::NONE { write!(f, "none") } else { let name = strings.lookup_bytes(id); FmtEscapedString(&name).fmt(f) } } } pub struct FmtRawBid(pub BlockId); impl Display for FmtRawBid { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let FmtRawBid(bid) = *self; if bid == BlockId::NONE { f.write_str("none") } else { write!(f, "b{}", bid.as_usize()) } } } pub struct FmtRawVid(pub ValueId); impl Display for FmtRawVid { fn fmt(&self, f: &mut Formatter<'_>) -> Result { match self.0.full() { FullInstrId::Instr(iid) => { if iid == InstrId::NONE { f.write_str("%none") } else { write!(f, "%{}", iid.as_usize()) } } FullInstrId::Constant(cid) => { if cid == ConstantId::NONE { f.write_str("#none") } else { write!(f, "#{}", cid.as_usize()) } } FullInstrId::None => f.write_str("none"), } } } pub(crate) struct FmtReadonly(pub(crate) ReadonlyOp); impl Display for FmtReadonly { fn fmt(&self, f: &mut Formatter<'_>) -> Result { match self.0 { ReadonlyOp::Readonly => write!(f, "readonly"), ReadonlyOp::Mutable => write!(f, "mutable"), ReadonlyOp::Any => write!(f, "any"), ReadonlyOp::CheckROCOW => write!(f, "check_ro_cow"), ReadonlyOp::CheckMutROCOW => write!(f, "check_mut_ro_cow"), _ => panic!("bad ReadonlyOp value"), } } } pub(crate) struct FmtSpecialClsRef(pub(crate) SpecialClsRef); impl Display for FmtSpecialClsRef { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let s = match self.0 { SpecialClsRef::LateBoundCls => "late_bound", SpecialClsRef::SelfCls => "self", SpecialClsRef::ParentCls => "parent", _ => panic!("bad SpecialClsRef value"), }; f.write_str(s) } } pub(crate) struct FmtTParams<'a>( pub(crate) &'a ClassIdMap<TParamBounds>, pub &'a StringInterner, ); impl Display for FmtTParams<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let FmtTParams(map, strings) = self; if map.is_empty() { Ok(()) } else { write!( f, // Since tparams end with '>' we need an extra space to make // sure we don't confuse with '>>'. "<{} >", FmtSep::comma(map.iter(), |f, (name, bounds)| { FmtIdentifierId(name.id, strings).fmt(f)?; if !bounds.bounds.is_empty() { write!(f, ": ")?; let mut sep = ""; for bound in bounds.bounds.iter() { write!(f, "{sep}{}", FmtTypeInfo(bound, strings))?; sep = " + "; } } Ok(()) }) ) } } } pub(crate) struct FmtShadowedTParams<'a>( pub(crate) &'a Vec<ClassId>, pub(crate) &'a StringInterner, ); impl Display for FmtShadowedTParams<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let FmtShadowedTParams(vec, strings) = *self; if vec.is_empty() { Ok(()) } else { write!( f, "[{}]", FmtSep::comma(vec.iter(), |f, name| { FmtIdentifierId(name.id, strings).fmt(f) }) ) } } } pub(crate) struct FmtTypedValue<'a>(pub &'a TypedValue, pub &'a StringInterner); impl Display for FmtTypedValue<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let FmtTypedValue(tv, strings) = *self; match tv { TypedValue::Uninit => write!(f, "uninit"), TypedValue::Int(v) => { write!(f, "{}", v) } TypedValue::Bool(b) => f.write_str(if *b { "true" } else { "false" }), TypedValue::String(v) => FmtEscapedString(&strings.lookup_bytes(*v)).fmt(f), TypedValue::Float(v) => FmtFloat(v.to_f64()).fmt(f), TypedValue::LazyClass(lit) => { write!(f, "lazy({})", FmtQuotedStringId(lit.id, strings)) } TypedValue::Null => f.write_str("null"), TypedValue::Vec(values) => { write!( f, "vec[{}]", FmtSep::comma(values.iter(), |f, v| { FmtTypedValue(v, strings).fmt(f) }) ) } TypedValue::Keyset(values) => { write!( f, "keyset[{}]", FmtSep::comma(values.iter(), |f, v| { FmtArrayKey(v, strings).fmt(f) }) ) } TypedValue::Dict(values) => { write!( f, "dict[{}]", FmtSep::comma(values.iter(), |f, (key, value)| { write!( f, "{} => {}", FmtArrayKey(key, strings), FmtTypedValue(value, strings) ) }) ) } } } } pub(crate) struct FmtArrayKey<'a>(pub &'a ArrayKey, pub &'a StringInterner); impl Display for FmtArrayKey<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let FmtArrayKey(tv, strings) = *self; match tv { ArrayKey::Int(v) => { write!(f, "{}", v) } ArrayKey::String(v) => FmtEscapedString(&strings.lookup_bytes(*v)).fmt(f), ArrayKey::LazyClass(v) => write!(f, "lazy({})", FmtQuotedStringId(v.id, strings)), } } } pub(crate) struct FmtVisibility(pub Visibility); impl Display for FmtVisibility { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let vis = match self.0 { Visibility::Private => "private", Visibility::Public => "public", Visibility::Protected => "protected", Visibility::Internal => "internal", }; vis.fmt(f) } } pub struct FmtEnforceableType<'a>(pub &'a EnforceableType, pub &'a StringInterner); impl<'a> Display for FmtEnforceableType<'a> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { self.0.write(f, self.1) } } pub(crate) struct FmtTypeInfo<'a>(pub &'a TypeInfo, pub &'a StringInterner); impl<'a> Display for FmtTypeInfo<'a> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let FmtTypeInfo(ti, strings) = self; write!(f, "<")?; if let Some(id) = ti.user_type { FmtQuotedStringId(id, strings).fmt(f)?; } else { f.write_str("N")?; } f.write_str(" ")?; match ti.enforced.ty { BaseType::AnyArray => f.write_str("array")?, BaseType::Arraykey => f.write_str("arraykey")?, BaseType::Bool => f.write_str("bool")?, BaseType::Class(cid) => write!(f, "class {}", FmtIdentifierId(cid.id, strings))?, BaseType::Classname => f.write_str("classname")?, BaseType::Darray => f.write_str("darray")?, BaseType::Dict => f.write_str("dict")?, BaseType::Float => f.write_str("float")?, BaseType::Int => f.write_str("int")?, BaseType::Keyset => f.write_str("keyset")?, BaseType::Mixed => f.write_str("mixed")?, BaseType::None => f.write_str("none")?, BaseType::Nonnull => f.write_str("nonnull")?, BaseType::Noreturn => f.write_str("noreturn")?, BaseType::Nothing => f.write_str("nothing")?, BaseType::Null => f.write_str("null")?, BaseType::Num => f.write_str("num")?, BaseType::Resource => f.write_str("resource")?, BaseType::String => f.write_str("string")?, BaseType::This => f.write_str("this")?, BaseType::Typename => f.write_str("typename")?, BaseType::Varray => f.write_str("varray")?, BaseType::VarrayOrDarray => f.write_str("varray_or_darray")?, BaseType::Vec => f.write_str("vec")?, BaseType::VecOrDict => f.write_str("vec_or_dict")?, BaseType::Void => f.write_str("void")?, } use TypeConstraintFlags as TCF; let mut mods = ti.enforced.modifiers; [ get_bit(&mut mods, TCF::DisplayNullable, "display_nullable"), get_bit(&mut mods, TCF::ExtendedHint, "extended"), get_bit(&mut mods, TCF::Nullable, "nullable"), get_bit(&mut mods, TCF::Resolved, "resolved"), get_bit(&mut mods, TCF::Soft, "soft"), get_bit(&mut mods, TCF::TypeConstant, "type_constant"), get_bit(&mut mods, TCF::TypeVar, "type_var"), get_bit(&mut mods, TCF::UpperBound, "upper_bound"), ] .into_iter() .flatten() .try_for_each(|s| write!(f, " {s}"))?; assert!(mods == TCF::NoFlags, "MOD: {:?}", ti.enforced.modifiers); write!(f, ">")?; Ok(()) } }
Rust
hhvm/hphp/hack/src/hackc/ir/print/lib.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. pub mod formatters; pub mod print; pub mod util; use std::fmt; pub use formatters::FmtBid; pub use formatters::FmtEnforceableType; pub use formatters::FmtInstr; pub use formatters::FmtLid; pub use formatters::FmtLoc; pub use formatters::FmtLocId; pub use formatters::FmtRawBid; pub use formatters::FmtRawVid; pub use formatters::FmtVid; use ir_core::BlockId; use ir_core::Func; use ir_core::InstrId; use ir_core::InstrIdSet; use ir_core::StringInterner; pub use print::print_unit; pub use util::FmtEscapedString; pub use util::FmtOption; pub use util::FmtOptionOr; pub use util::FmtSep; // This isn't used by the print crate but is useful for code that wants to print // a Func for debugging purposes. pub struct DisplayFunc<'a, 'b> { pub func: &'b Func<'a>, /* verbose */ pub verbose: bool, pub strings: &'b StringInterner, pub f_pre_block: Option<&'b dyn Fn(&mut dyn fmt::Write, BlockId) -> fmt::Result>, pub f_pre_instr: Option<&'b dyn Fn(&mut dyn fmt::Write, InstrId) -> fmt::Result>, } impl<'a, 'b> DisplayFunc<'a, 'b> { pub fn new(func: &'b Func<'a>, verbose: bool, strings: &'b StringInterner) -> Self { DisplayFunc { func, verbose, strings, f_pre_block: None, f_pre_instr: None, } } } impl fmt::Display for DisplayFunc<'_, '_> { fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result { let DisplayFunc { func, verbose, strings, f_pre_block, f_pre_instr, } = *self; writeln!(w, "func {} {{", formatters::FmtFuncParams(func, strings))?; print::print_func_body(w, func, verbose, strings, f_pre_block, f_pre_instr)?; writeln!(w, "}}")?; if verbose { let mut unused: InstrIdSet = (0..func.instrs.len()).map(InstrId::from_usize).collect(); for iid in func.body_iids() { unused.remove(&iid); } for iid in func .block_ids() .flat_map(|bid| func.block(bid).params.iter().copied()) { unused.remove(&iid); } if !unused.is_empty() { let mut unused: Vec<InstrId> = unused.into_iter().collect(); unused.sort(); writeln!(w, "unowned:")?; for iid in unused { writeln!(w, " {iid}: {:?}", func.instrs[iid])?; } } } writeln!(w) } }
Rust
hhvm/hphp/hack/src/hackc/ir/print/print.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. //! Print Functions //! //! These functions are used to print the IR in a pseudo-assembly format. //! //! The functions in this file (as opposed to formatters.rs) print full (or //! more) lines of IR. As a result they mostly will be in the form //! `print_thing(thing: &Thing)`. //! use std::fmt::Display; use std::fmt::Error; use std::fmt::Result; use std::fmt::Write; use ir_core::class::Property; use ir_core::instr::BaseOp; use ir_core::instr::FinalOp; use ir_core::instr::HasLoc; use ir_core::instr::Hhbc; use ir_core::instr::IncludeKind; use ir_core::instr::IrToBc; use ir_core::instr::MemberKey; use ir_core::instr::Special; use ir_core::instr::Terminator; use ir_core::instr::Tmp; use ir_core::unit::SymbolRefs; use ir_core::*; use crate::formatters::*; use crate::util::FmtSep; use crate::FmtEscapedString; pub(crate) struct FuncContext<'a> { pub(crate) cur_loc_id: LocId, pub(crate) live_instrs: InstrIdSet, pub(crate) strings: &'a StringInterner, pub(crate) verbose: bool, } fn print_binary_op(w: &mut dyn Write, ctx: &FuncContext<'_>, func: &Func<'_>, op: &Hhbc) -> Result { let (prefix, infix, lhs, rhs) = match *op { Hhbc::Add([lhs, rhs], _) => ("add", ",", lhs, rhs), Hhbc::BitAnd([lhs, rhs], _) => ("bit_and", ",", lhs, rhs), Hhbc::BitOr([lhs, rhs], _) => ("bit_or", ",", lhs, rhs), Hhbc::BitXor([lhs, rhs], _) => ("bit_xor", ",", lhs, rhs), Hhbc::Cmp([lhs, rhs], _) => ("cmp", " <=>", lhs, rhs), Hhbc::CmpOp([lhs, rhs], op, _) => { use instr::CmpOp; let op = match op { CmpOp::Eq => " ==", CmpOp::Gt => " >", CmpOp::Gte => " >=", CmpOp::Lt => " <", CmpOp::Lte => " <=", CmpOp::NSame => " !==", CmpOp::Neq => " !=", CmpOp::Same => " ===", }; ("cmp", op, lhs, rhs) } Hhbc::Concat([lhs, rhs], _) => ("concat", ",", lhs, rhs), Hhbc::Div([lhs, rhs], _) => ("div", ",", lhs, rhs), Hhbc::IsTypeStructC([lhs, rhs], op, _) => { let op = match op { TypeStructResolveOp::Resolve => " resolve", TypeStructResolveOp::DontResolve => " dont_resolve", _ => panic!("bad TypeStructResolveOp value"), }; ("is_type_struct_c", op, lhs, rhs) } Hhbc::Modulo([lhs, rhs], _) => ("mod", ",", lhs, rhs), Hhbc::Mul([lhs, rhs], _) => ("mul", ",", lhs, rhs), Hhbc::Pow([lhs, rhs], _) => ("pow", ",", lhs, rhs), Hhbc::Shl([lhs, rhs], _) => ("shl", ",", lhs, rhs), Hhbc::Shr([lhs, rhs], _) => ("shr", ",", lhs, rhs), Hhbc::Sub([lhs, rhs], _) => ("sub", ",", lhs, rhs), _ => unreachable!(), }; write!( w, "{} {}{} {}", prefix, FmtVid(func, lhs, ctx.verbose, ctx.strings), infix, FmtVid(func, rhs, ctx.verbose, ctx.strings) ) } fn print_call(w: &mut dyn Write, ctx: &FuncContext<'_>, func: &Func<'_>, call: &Call) -> Result { let verbose = ctx.verbose; let strings = ctx.strings; use instr::CallDetail; match &call.detail { CallDetail::FCallClsMethod { log } => { let dc = match *log { IsLogAsDynamicCallOp::LogAsDynamicCall => " log_as_dc", IsLogAsDynamicCallOp::DontLogAsDynamicCall => "", _ => panic!("bad IsLogAsDynamicCallOp value"), }; write!( w, "call cls_method {}::{}{}", FmtVid(func, call.detail.class(&call.operands), verbose, strings), FmtVid(func, call.detail.method(&call.operands), verbose, strings), dc )?; } CallDetail::FCallClsMethodD { clsid, method } => { write!( w, "call cls_method {}::{}", FmtIdentifierId(clsid.id, ctx.strings), FmtIdentifierId(method.id, ctx.strings), )?; } CallDetail::FCallClsMethodM { method, log } => { let dc = match *log { IsLogAsDynamicCallOp::LogAsDynamicCall => " log_as_dc", IsLogAsDynamicCallOp::DontLogAsDynamicCall => "", _ => panic!("bad IsLogAsDynamicCallOp value"), }; write!( w, "call cls_method {}::{}{}", FmtVid(func, call.detail.class(&call.operands), verbose, strings), FmtIdentifierId(method.id, ctx.strings), dc )?; } CallDetail::FCallClsMethodS { clsref } => { write!( w, "call cls_method {}::{}", FmtSpecialClsRef(*clsref), FmtVid(func, call.detail.method(&call.operands), verbose, strings), )?; } CallDetail::FCallClsMethodSD { clsref, method } => { write!( w, "call cls_method {}::{}", FmtSpecialClsRef(*clsref), FmtIdentifierId(method.id, ctx.strings), )?; } CallDetail::FCallCtor => { write!( w, "call ctor {}", FmtVid(func, call.detail.obj(&call.operands), verbose, strings) )?; } CallDetail::FCallFunc => { write!( w, "call func {}", FmtVid(func, call.detail.target(&call.operands), verbose, strings) )?; } CallDetail::FCallFuncD { func } => { write!(w, "call func {}", FmtIdentifierId(func.id, ctx.strings))?; } CallDetail::FCallObjMethod { flavor } => { let arrow = match *flavor { ObjMethodOp::NullThrows => "->", ObjMethodOp::NullSafe => "?->", _ => unreachable!(), }; write!( w, "call obj_method {}{arrow}{}", FmtVid(func, call.detail.obj(&call.operands), verbose, strings), FmtVid(func, call.detail.method(&call.operands), verbose, strings) )?; } CallDetail::FCallObjMethodD { method, flavor } => { let arrow = match *flavor { ObjMethodOp::NullThrows => "->", ObjMethodOp::NullSafe => "?->", _ => unreachable!(), }; write!( w, "call obj_method {}{arrow}{}", FmtVid(func, call.detail.obj(&call.operands), verbose, strings), FmtIdentifierId(method.id, ctx.strings) )?; } } let mut inout_iter = call .inouts .as_ref() .map_or_else(|| [].iter(), |inouts| inouts.iter()) .copied() .peekable(); let mut readonly_iter = call .readonly .as_ref() .map_or_else(|| [].iter(), |readonly| readonly.iter()) .copied() .peekable(); let args = call.args().iter().enumerate().map(|(idx, arg)| { let idx = idx as u32; let inout = inout_iter.next_if_eq(&idx).is_some(); let readonly = readonly_iter.next_if_eq(&idx).is_some(); (arg, inout, readonly) }); write!( w, "({})", FmtSep::comma(args, |w, (arg, inout, readonly)| { let inout = if inout { "inout " } else { "" }; let readonly = if readonly { "readonly " } else { "" }; write!( w, "{}{}{}", readonly, inout, FmtVid(func, *arg, verbose, strings) ) }) )?; let num_inouts: u32 = call.inouts.as_ref().map_or(0, |inouts| inouts.len()) as u32; if call.num_rets != 1 + num_inouts { write!(w, " num_rets({})", call.num_rets)?; } if call.flags.contains(FCallArgsFlags::HasUnpack) { write!(w, " has_unpack")?; } if call.flags.contains(FCallArgsFlags::HasGenerics) { write!(w, " has_generics")?; } if call.flags.contains(FCallArgsFlags::LockWhileUnwinding) { write!(w, " lock_while_unwinding")?; } if call.flags.contains(FCallArgsFlags::EnforceMutableReturn) { write!(w, " enforce_mutable_return")?; } if call.flags.contains(FCallArgsFlags::EnforceReadonlyThis) { write!(w, " enforce_readonly_this")?; } if call.flags.contains(FCallArgsFlags::SkipRepack) { write!(w, " skip_repack")?; } if call.flags.contains(FCallArgsFlags::SkipCoeffectsCheck) { write!(w, " skip_coeffects_check")?; } if call.flags.contains(FCallArgsFlags::ExplicitContext) { write!(w, " explicit_context")?; } if call.flags.contains(FCallArgsFlags::HasInOut) { write!(w, " has_in_out")?; } if call.flags.contains(FCallArgsFlags::EnforceInOut) { write!(w, " enforce_in_out")?; } if call.flags.contains(FCallArgsFlags::EnforceReadonly) { write!(w, " enforce_readonly")?; } if call.flags.contains(FCallArgsFlags::HasAsyncEagerOffset) { write!(w, " has_async_eager_offset")?; } if call.flags.contains(FCallArgsFlags::NumArgsStart) { write!(w, " num_args_start")?; } write!(w, " {}", FmtQuotedStringId(call.context, ctx.strings))?; Ok(()) } fn print_call_async( w: &mut dyn Write, ctx: &FuncContext<'_>, func: &Func<'_>, call: &Call, targets: &[BlockId; 2], ) -> Result { write!(w, "async_")?; print_call(w, ctx, func, call)?; write!( w, " to {} eager {}", FmtBid(func, targets[0], ctx.verbose), FmtBid(func, targets[1], ctx.verbose), ) } fn print_class(w: &mut dyn Write, class: &Class<'_>, strings: &StringInterner) -> Result { print_top_level_loc(w, Some(&class.src_loc), strings)?; writeln!( w, "class {} {} {{", FmtIdentifierId(class.name.id, strings), FmtAttr(class.flags, AttrContext::Class) )?; if let Some(doc_comment) = class.doc_comment.as_ref() { writeln!(w, " doc_comment {}", FmtQuotedStr(doc_comment))?; } if let Some(base) = class.base { writeln!(w, " extends {}", FmtIdentifierId(base.id, strings))?; } for implement in &class.implements { writeln!(w, " implements {}", FmtIdentifierId(implement.id, strings))?; } if let Some(et) = class.enum_type.as_ref() { writeln!(w, " enum_type {}", FmtTypeInfo(et, strings))?; } if !class.enum_includes.is_empty() { writeln!( w, " enum_includes {}", FmtSep::comma(class.enum_includes.iter(), |w, ie| FmtIdentifierId( ie.id, strings ) .fmt(w)) )?; } for (name, tys) in &class.upper_bounds { writeln!( w, " upper_bound {}: [{}]", FmtIdentifier(name.as_ref()), FmtSep::comma(tys.iter(), |w, ty| FmtTypeInfo(ty, strings).fmt(w)) )?; } for ctx in &class.ctx_constants { print_ctx_constant(w, ctx)?; } for tc in &class.type_constants { print_type_constant(w, tc, strings)?; } for use_ in &class.uses { writeln!(w, " uses {}", FmtIdentifierId(use_.id, strings))?; } for req in &class.requirements { let kind = match req.kind { TraitReqKind::MustExtend => "extends", TraitReqKind::MustImplement => "implements", TraitReqKind::MustBeClass => "must_be_class", }; writeln!( w, " require {} {}", kind, FmtIdentifierId(req.name.id, strings) )?; } for prop in &class.properties { print_property(w, prop, strings)?; } for attr in &class.attributes { writeln!(w, " attribute {}", FmtAttribute(attr, strings))?; } for c in &class.constants { write!(w, " ")?; print_hack_constant(w, c, strings)?; } for method in &class.methods { writeln!(w, " method {}", FmtIdentifierId(method.name.id, strings))?; } writeln!(w, "}}")?; writeln!(w) } pub(crate) fn print_coeffects(w: &mut dyn Write, coeffects: &Coeffects<'_>) -> Result { if !coeffects.static_coeffects.is_empty() || !coeffects.unenforced_static_coeffects.is_empty() { write!( w, " .coeffects_static enforced({})", FmtSep::comma(coeffects.static_coeffects.iter(), |f, v| v.fmt(f)) )?; if !coeffects.unenforced_static_coeffects.is_empty() { write!( w, " unenforced({})", FmtSep::comma(coeffects.unenforced_static_coeffects.iter(), |f, v| { FmtIdentifier(v).fmt(f) }) )?; } writeln!(w)?; } if !coeffects.fun_param.is_empty() { writeln!( w, " .coeffects_fun_param {}", FmtSep::comma(coeffects.fun_param.iter(), |w, v| write!(w, "{v}")) )?; } for CcParam { index, ctx_name } in &coeffects.cc_param { writeln!(w, ".coeffects_cc_param {index} {}", FmtQuotedStr(ctx_name))?; } for CcThis { types } in &coeffects.cc_this { writeln!( w, ".coeffects_cc_this {}", FmtSep::comma(types.iter(), |f, v| { FmtQuotedStr(v).fmt(f) }) )?; } for CcReified { is_class, index, types, } in &coeffects.cc_reified { writeln!( w, " .coeffects_cc_reified {}{} {}", if *is_class { "is_class " } else { "" }, index, FmtSep::new("", "::", "", types.iter(), |w, qn| FmtIdentifier(qn).fmt(w)) )?; } if coeffects.closure_parent_scope { writeln!(w, " .coeffects_closure_parent_scope")?; } if coeffects.generator_this { writeln!(w, " .coeffects_generator_this")?; } if coeffects.caller { writeln!(w, " .coeffects_caller")?; } Ok(()) } fn print_ctx_constant(w: &mut dyn Write, ctx: &CtxConstant<'_>) -> Result { writeln!( w, " ctx_constant {} [{}] [{}]{}", FmtIdentifier(&ctx.name), FmtSep::comma(ctx.recognized.iter(), |w, i| FmtIdentifier(i).fmt(w)), FmtSep::comma(ctx.unrecognized.iter(), |w, i| FmtIdentifier(i).fmt(w)), if ctx.is_abstract { " abstract" } else { "" } ) } pub(crate) fn print_fatal( w: &mut dyn Write, fatal: Option<&Fatal>, strings: &StringInterner, ) -> Result { if let Some(Fatal { op, loc, message }) = fatal { let what = match *op { ir_core::FatalOp::Parse => "parse", ir_core::FatalOp::Runtime => "runtime", ir_core::FatalOp::RuntimeOmitFrame => "runtime_omit_frame", _ => unreachable!(), }; print_top_level_loc(w, Some(loc), strings)?; writeln!( w, ".fatal {} {}\n", what, FmtQuotedStr(&ffi::Str::new(message)) )?; } Ok(()) } pub(crate) fn print_func_body( w: &mut dyn Write, func: &Func<'_>, verbose: bool, strings: &StringInterner, f_pre_block: Option<&dyn Fn(&mut dyn Write, BlockId) -> Result>, f_pre_instr: Option<&dyn Fn(&mut dyn Write, InstrId) -> Result>, ) -> Result { if let Some(doc_comment) = func.doc_comment.as_ref() { writeln!(w, " .doc {}", FmtQuotedStr(doc_comment))?; } if func.num_iters != 0 { writeln!(w, " .num_iters {}", func.num_iters)?; } if func.is_memoize_wrapper { writeln!(w, " .is_memoize_wrapper")?; } if func.is_memoize_wrapper_lsb { writeln!(w, " .is_memoize_wrapper_lsb")?; } for cid in func.constants.keys() { writeln!( w, " .const {} = {}", FmtRawVid(ValueId::from_constant(cid)), FmtConstantId(func, cid, strings), )?; } for (id, func::ExFrame { parent, catch_bid }) in &func.ex_frames { write!( w, " .ex_frame {}: catch={}", id.as_usize(), FmtBid(func, *catch_bid, verbose) )?; match parent { TryCatchId::None => {} TryCatchId::Try(id) => write!(w, ", parent=try({})", id.as_usize())?, TryCatchId::Catch(id) => write!(w, ", parent=catch({})", id.as_usize())?, } writeln!(w)?; } let live_instrs = crate::util::compute_live_instrs(func, verbose); let mut ctx = FuncContext { cur_loc_id: func.loc_id, live_instrs, strings, verbose, }; for bid in func.blocks.keys() { let block = &func.blocks[bid]; write!(w, "{}", FmtBid(func, bid, false))?; if !block.params.is_empty() { write!( w, "({})", FmtSep::comma(&block.params, |w, iid| FmtVid( func, ValueId::from_instr(*iid), verbose, strings ) .fmt(w)) )?; } writeln!(w, ":")?; if let Some(f_pre_block) = f_pre_block.as_ref() { f_pre_block(w, bid)?; } match block.tcid { TryCatchId::None => {} TryCatchId::Try(id) => writeln!(w, " .try_id {}", id.as_usize())?, TryCatchId::Catch(id) => writeln!(w, " .catch_id {}", id.as_usize())?, } for iid in block.iids() { if let Some(f_pre_instr) = f_pre_instr.as_ref() { f_pre_instr(w, iid)?; } let instr = func.instr(iid); if crate::print::print_instr(w, &mut ctx, func, iid, instr)? { writeln!(w)?; } } } Ok(()) } fn print_attributes(w: &mut dyn Write, attrs: &[Attribute], strings: &StringInterner) -> Result { for attr in attrs { writeln!(w, " .attr {}", FmtAttribute(attr, strings))?; } Ok(()) } fn print_top_level_loc( w: &mut dyn Write, src_loc: Option<&SrcLoc>, strings: &StringInterner, ) -> Result { if let Some(loc) = src_loc { writeln!(w, ".srcloc {}", FmtFullLoc(loc, strings))?; } else { writeln!(w, ".srcloc none")?; } Ok(()) } fn print_function( w: &mut dyn Write, f: &Function<'_>, verbose: bool, strings: &StringInterner, ) -> Result { print_top_level_loc(w, f.func.get_loc(f.func.loc_id), strings)?; writeln!( w, "function {name}{tparams}{params}{shadowed_tparams}: {ret_type} {attr} {{", name = FmtIdentifierId(f.name.id, strings), tparams = FmtTParams(&f.func.tparams, strings), shadowed_tparams = FmtShadowedTParams(&f.func.shadowed_tparams, strings), params = FmtFuncParams(&f.func, strings), ret_type = FmtTypeInfo(&f.func.return_type, strings), attr = FmtAttr(f.attrs, AttrContext::Function), )?; print_function_flags(w, f.flags)?; print_attributes(w, &f.attributes, strings)?; print_coeffects(w, &f.coeffects)?; print_func_body(w, &f.func, verbose, strings, None, None)?; writeln!(w, "}}")?; writeln!(w) } fn print_function_flags(w: &mut dyn Write, mut flags: FunctionFlags) -> Result { [ get_bit(&mut flags, FunctionFlags::ASYNC, ".async"), get_bit(&mut flags, FunctionFlags::GENERATOR, ".generator"), get_bit(&mut flags, FunctionFlags::PAIR_GENERATOR, ".pair_generator"), get_bit(&mut flags, FunctionFlags::MEMOIZE_IMPL, ".memoize_impl"), ] .into_iter() .flatten() .try_for_each(|f| writeln!(w, " {f}")) } fn print_hhbc(w: &mut dyn Write, ctx: &FuncContext<'_>, func: &Func<'_>, hhbc: &Hhbc) -> Result { let verbose = ctx.verbose; let strings = ctx.strings; match *hhbc { Hhbc::Add(..) | Hhbc::BitAnd(..) | Hhbc::BitOr(..) | Hhbc::BitXor(..) | Hhbc::Cmp(..) | Hhbc::CmpOp(..) | Hhbc::Concat(..) | Hhbc::Div(..) | Hhbc::IsTypeStructC(..) | Hhbc::Modulo(..) | Hhbc::Mul(..) | Hhbc::Pow(..) | Hhbc::Shl(..) | Hhbc::Shr(..) | Hhbc::Sub(..) => print_binary_op(w, ctx, func, hhbc)?, Hhbc::AKExists(ops, _) => { write!( w, "ak_exists {}, {}", FmtVid(func, ops[0], verbose, strings), FmtVid(func, ops[1], verbose, strings) )?; } Hhbc::AddElemC(ops, _) => { write!( w, "add_elem_c {}[{}] = {}", FmtVid(func, ops[0], verbose, strings), FmtVid(func, ops[1], verbose, strings), FmtVid(func, ops[2], verbose, strings), )?; } Hhbc::AddNewElemC(ops, _) => { write!( w, "add_new_elem_c {}[] = {}", FmtVid(func, ops[0], verbose, strings), FmtVid(func, ops[1], verbose, strings), )?; } Hhbc::ArrayIdx(vids, _) => { write!( w, "array_idx {}[{}] or {}", FmtVid(func, vids[0], verbose, strings), FmtVid(func, vids[1], verbose, strings), FmtVid(func, vids[2], verbose, strings) )?; } Hhbc::ArrayMarkLegacy(vids, _) => { write!( w, "array_mark_legacy {}, {}", FmtVid(func, vids[0], verbose, strings), FmtVid(func, vids[1], verbose, strings) )?; } Hhbc::ArrayUnmarkLegacy(vids, _) => { write!( w, "array_unmark_legacy {}, {}", FmtVid(func, vids[0], verbose, strings), FmtVid(func, vids[1], verbose, strings) )?; } Hhbc::Await(vid, _) => { write!(w, "await {}", FmtVid(func, vid, verbose, strings))?; } Hhbc::AwaitAll(ref range, _) => { write!(w, "await_all {}", FmtLids(range, ctx.strings),)?; } Hhbc::BareThis(op, _) => { write!(w, "bare_this {}", FmtBareThisOp(op))?; } Hhbc::BitNot(vid, _) => write!(w, "bit_not {}", FmtVid(func, vid, ctx.verbose, strings),)?, Hhbc::CGetG(vid, _) => write!(w, "get_global {}", FmtVid(func, vid, verbose, strings))?, Hhbc::CGetL(lid, _) => write!(w, "get_local {}", FmtLid(lid, ctx.strings))?, Hhbc::CGetQuietL(lid, _) => write!(w, "get_local_quiet {}", FmtLid(lid, ctx.strings))?, Hhbc::CGetS(vids, readonly, _) => write!( w, "get_static {}->{} {}", FmtVid(func, vids[1], verbose, strings), FmtVid(func, vids[0], verbose, strings), FmtReadonly(readonly) )?, Hhbc::CUGetL(lid, _) => write!(w, "get_local_or_uninit {}", FmtLid(lid, ctx.strings))?, Hhbc::CastBool(vid, _) => { write!(w, "cast_bool {}", FmtVid(func, vid, ctx.verbose, strings),)? } Hhbc::CastDict(vid, _) => { write!(w, "cast_dict {}", FmtVid(func, vid, ctx.verbose, strings),)? } Hhbc::CastDouble(vid, _) => { write!(w, "cast_double {}", FmtVid(func, vid, ctx.verbose, strings),)? } Hhbc::CastInt(vid, _) => { write!(w, "cast_int {}", FmtVid(func, vid, ctx.verbose, strings),)? } Hhbc::CastKeyset(vid, _) => { write!(w, "cast_keyset {}", FmtVid(func, vid, ctx.verbose, strings),)? } Hhbc::CastString(vid, _) => { write!(w, "cast_string {}", FmtVid(func, vid, ctx.verbose, strings),)? } Hhbc::CastVec(vid, _) => { write!(w, "cast_vec {}", FmtVid(func, vid, ctx.verbose, strings),)? } Hhbc::ChainFaults(ops, _) => { write!( w, "chain_faults {}, {}", FmtVid(func, ops[0], verbose, strings), FmtVid(func, ops[1], verbose, strings) )?; } Hhbc::CheckClsReifiedGenericMismatch(vid, _) => { write!( w, "check_cls_reified_generic_mismatch {}", FmtVid(func, vid, verbose, strings) )?; } Hhbc::CheckClsRGSoft(vid, _) => { write!( w, "check_cls_rg_soft {}", FmtVid(func, vid, verbose, strings) )?; } Hhbc::CheckProp(prop, _) => { write!(w, "check_prop {}", FmtIdentifierId(prop.id, ctx.strings))? } Hhbc::CheckThis(_) => { write!(w, "check_this")?; } Hhbc::ClassGetC(vid, _) => { write!(w, "class_get_c {}", FmtVid(func, vid, verbose, strings))? } Hhbc::ClassGetTS(vid, _) => { write!(w, "class_get_ts {}", FmtVid(func, vid, verbose, strings))? } Hhbc::ClassHasReifiedGenerics(vid, _) => write!( w, "class_has_reified_generics {}", FmtVid(func, vid, verbose, strings) )?, Hhbc::ClassName(vid, _) => { write!(w, "class_name {}", FmtVid(func, vid, verbose, strings))?; } Hhbc::Clone(vid, _) => write!(w, "clone {}", FmtVid(func, vid, ctx.verbose, strings),)?, Hhbc::ClsCns(clsid, id, _) => { write!( w, "cls_cns {}::{}", FmtVid(func, clsid, verbose, strings), FmtIdentifierId(id.id, ctx.strings) )?; } Hhbc::ClsCnsD(id, clsid, _) => { write!( w, "cls_cns_d {}::{}", FmtIdentifierId(clsid.id, ctx.strings), FmtIdentifierId(id.id, ctx.strings) )?; } Hhbc::ClsCnsL(vid, lid, _) => { write!( w, "cls_cns_l {}::{}", FmtVid(func, vid, verbose, strings), FmtLid(lid, ctx.strings) )?; } Hhbc::ColFromArray(vid, kind, _) => { write!( w, "col_from_array {} {}", FmtCollectionType(kind), FmtVid(func, vid, verbose, strings) )?; } Hhbc::CombineAndResolveTypeStruct(ref vids, _) => { write!( w, "combine_and_resolve_type_struct {}", FmtSep::comma(vids.iter(), |w, vid| FmtVid(func, *vid, verbose, strings) .fmt(w)) )?; } Hhbc::ConcatN(ref vids, _) => { write!( w, "concatn {}", FmtSep::comma(vids.iter(), |w, vid| FmtVid(func, *vid, verbose, strings) .fmt(w)) )?; } Hhbc::ConsumeL(lid, _) => { write!(w, "consume_local {}", FmtLid(lid, ctx.strings))?; } Hhbc::ContCheck(kind, _) => { let kind = match kind { ContCheckOp::IgnoreStarted => "ignore", ContCheckOp::CheckStarted => "check", _ => panic!("bad ContCheckOp value"), }; write!(w, "cont_check {}", kind)?; } Hhbc::ContCurrent(_) => { write!(w, "cont_current")?; } Hhbc::ContEnter(vid, _) => { write!(w, "cont_enter {}", FmtVid(func, vid, verbose, strings))?; } Hhbc::ContGetReturn(_) => { write!(w, "cont_get_return")?; } Hhbc::ContKey(_) => { write!(w, "cont_key")?; } Hhbc::ContRaise(vid, _) => { write!(w, "cont_raise {}", FmtVid(func, vid, verbose, strings))?; } Hhbc::ContValid(_) => { write!(w, "cont_valid")?; } Hhbc::CreateCl { ref operands, clsid, loc: _, } => { write!( w, "create_class {}({})", FmtIdentifierId(clsid.id, ctx.strings), FmtSep::comma(operands.iter(), |w, arg| write!( w, "{}", FmtVid(func, *arg, verbose, strings) )) )?; } Hhbc::CreateCont(_) => write!(w, "create_cont")?, Hhbc::CreateSpecialImplicitContext(vids, _) => { write!( w, "create_special_implicit_context {}, {}", FmtVid(func, vids[0], verbose, strings), FmtVid(func, vids[1], verbose, strings) )?; } Hhbc::GetClsRGProp(vid, _) => write!( w, "get_class_rg_prop {}", FmtVid(func, vid, verbose, strings) )?, Hhbc::GetMemoKeyL(lid, _) => { write!(w, "get_memo_key {}", FmtLid(lid, ctx.strings))?; } Hhbc::HasReifiedParent(vid, _) => write!( w, "has_reified_parent {}", FmtVid(func, vid, verbose, strings) )?, Hhbc::Idx(vids, _) => { write!( w, "idx {}[{}] or {}", FmtVid(func, vids[0], verbose, strings), FmtVid(func, vids[1], verbose, strings), FmtVid(func, vids[2], verbose, strings), )?; } Hhbc::IncDecL(lid, op, _) => { let (pre, post) = incdec_what(op); let lid = FmtLid(lid, ctx.strings); write!(w, "incdec_local {}{}{}", pre, lid, post)?; } Hhbc::IncDecS([cls, prop], op, _) => { let (pre, post) = incdec_what(op); write!( w, "incdec_static_prop {}{}::{}{}", pre, FmtVid(func, cls, verbose, strings), FmtVid(func, prop, verbose, strings), post )?; } Hhbc::IncludeEval(ref ie) => print_include_eval(w, ctx, func, ie)?, Hhbc::InitProp(vid, prop, op, _) => { write!( w, "init_prop {}, {}, {}", FmtQuotedStringId(prop.id, ctx.strings), FmtVid(func, vid, verbose, strings), FmtInitPropOp(op) )?; } Hhbc::InstanceOfD(vid, clsid, _) => write!( w, "instance_of_d {}, {}", FmtVid(func, vid, ctx.verbose, strings), FmtIdentifierId(clsid.id, ctx.strings) )?, Hhbc::IsLateBoundCls(vid, _) => { write!( w, "is_late_bound_cls {}", FmtVid(func, vid, ctx.verbose, strings) )?; } Hhbc::IsTypeC(vid, op, _) => { write!( w, "is_type_c {}, {}", FmtVid(func, vid, ctx.verbose, strings), FmtIsTypeOp(op) )?; } Hhbc::IsTypeL(lid, op, _) => { write!( w, "is_type_l {}, {}", FmtLid(lid, ctx.strings), FmtIsTypeOp(op) )?; } Hhbc::IssetG(vid, _) => { write!(w, "isset_g {}", FmtVid(func, vid, verbose, strings))?; } Hhbc::IssetL(lid, _) => { write!(w, "isset_l {}", FmtLid(lid, ctx.strings))?; } Hhbc::IssetS([cls, prop], _) => { write!( w, "isset_s {}::{}", FmtVid(func, cls, verbose, strings), FmtVid(func, prop, verbose, strings) )?; } Hhbc::IterFree(iter_id, _loc) => { write!(w, "iterator ^{} free", iter_id.idx)?; } Hhbc::LateBoundCls(_) => { write!(w, "late_bound_cls")?; } Hhbc::LazyClass(clsid, _) => { write!(w, "lazy_class {}", FmtIdentifierId(clsid.id, ctx.strings))?; } Hhbc::LazyClassFromClass(vid, _) => { write!( w, "lazy_class_from_class {}", FmtVid(func, vid, verbose, strings) )?; } Hhbc::LockObj(vid, _) => { write!(w, "lock_obj {}", FmtVid(func, vid, verbose, strings))?; } Hhbc::MemoSet(vid, ref locals, _) => { write!( w, "memo_set {}, {}", FmtLids(locals, ctx.strings), FmtVid(func, vid, verbose, strings) )?; } Hhbc::MemoSetEager(vid, ref locals, _) => { write!( w, "memo_set_eager {}, {}", FmtLids(locals, ctx.strings), FmtVid(func, vid, verbose, strings) )?; } Hhbc::NewDictArray(hint, _) => { write!(w, "new_dict_array {}", hint)?; } Hhbc::NewKeysetArray(ref operands, _) => { write!( w, "new_keyset_array [{}]", FmtSep::comma(operands.iter(), |w, arg| write!( w, "{}", FmtVid(func, *arg, verbose, strings) )) )?; } Hhbc::NewObj(vid, _) => { write!(w, "new_obj {}", FmtVid(func, vid, verbose, strings))?; } Hhbc::NewObjD(clsid, _) => { write!( w, "new_obj direct {}", FmtIdentifierId(clsid.id, ctx.strings) )?; } Hhbc::NewObjS(clsref, _) => { write!(w, "new_obj static {}", FmtSpecialClsRef(clsref))?; } Hhbc::NewPair(vids, _) => { write!( w, "new_pair {}, {}", FmtVid(func, vids[0], verbose, strings), FmtVid(func, vids[1], verbose, strings) )?; } Hhbc::NewStructDict(ref keys, ref values, _) => { write!( w, "new_struct_dict [{}]", FmtSep::comma(keys.iter().zip(values.iter()), |w, (k, v)| { write!( w, "{} => {}", FmtQuotedStringId(*k, ctx.strings), FmtVid(func, *v, verbose, strings) ) }) )?; } Hhbc::NewVec(ref vids, _) => { write!( w, "new_vec [{}]", FmtSep::comma(vids.iter(), |w, vid| FmtVid(func, *vid, verbose, strings) .fmt(w)) )?; } Hhbc::Not(vid, _) => write!(w, "not {}", FmtVid(func, vid, ctx.verbose, strings))?, Hhbc::OODeclExists(vids, op, _) => { let kind = match op { OODeclExistsOp::Class => "class", OODeclExistsOp::Interface => "interface", OODeclExistsOp::Trait => "trait", _ => unreachable!(), }; write!( w, "oo_decl_exists {}, {} {}", FmtVid(func, vids[0], verbose, strings), FmtVid(func, vids[1], verbose, strings), kind )?; } Hhbc::ParentCls(_) => { write!(w, "parent")?; } Hhbc::Print(vid, _) => write!(w, "print {}", FmtVid(func, vid, ctx.verbose, strings))?, Hhbc::RaiseClassStringConversionWarning(_) => { write!(w, "raise_class_string_conversion_warning")? } Hhbc::RecordReifiedGeneric(vid, _) => write!( w, "record_reified_generic {}", FmtVid(func, vid, ctx.verbose, strings) )?, Hhbc::ResolveClass(clsid, _) => write!( w, "resolve_class {}", FmtIdentifierId(clsid.id, ctx.strings) )?, Hhbc::ResolveClsMethod(vid, method, _) => { write!( w, "resolve_cls_method {}::{}", FmtVid(func, vid, ctx.verbose, strings), FmtIdentifierId(method.id, ctx.strings), )?; } Hhbc::ResolveClsMethodD(clsid, method, _) => { write!( w, "resolve_cls_method_d {}::{}", FmtIdentifierId(clsid.id, ctx.strings), FmtIdentifierId(method.id, ctx.strings), )?; } Hhbc::ResolveClsMethodS(clsref, method, _) => { write!( w, "resolve_cls_method_s {}::{}", FmtSpecialClsRef(clsref), FmtIdentifierId(method.id, ctx.strings), )?; } Hhbc::ResolveRClsMethod([clsid, vid], method, _) => { write!( w, "resolve_r_cls_method {}::{}, {}", FmtVid(func, clsid, verbose, strings), FmtIdentifierId(method.id, ctx.strings), FmtVid(func, vid, verbose, strings), )?; } Hhbc::ResolveRClsMethodS(vid, clsref, method, _) => { write!( w, "resolve_r_cls_method_s {}::{}, {}", FmtSpecialClsRef(clsref), FmtIdentifierId(method.id, ctx.strings), FmtVid(func, vid, verbose, strings), )?; } Hhbc::ResolveFunc(func, _) => { write!(w, "resolve_func {}", FmtIdentifierId(func.id, ctx.strings))?; } Hhbc::ResolveRClsMethodD(vid, clsid, method, _) => { write!( w, "resolve_r_cls_method_d {}::{}, {}", FmtIdentifierId(clsid.id, ctx.strings), FmtIdentifierId(method.id, ctx.strings), FmtVid(func, vid, verbose, strings), )?; } Hhbc::ResolveRFunc(rid, fid, _) => { write!( w, "resolve_r_func {}, {}", FmtIdentifierId(fid.id, ctx.strings), FmtVid(func, rid, verbose, strings) )?; } Hhbc::ResolveMethCaller(func, _) => { write!( w, "resolve_meth_caller {}", FmtIdentifierId(func.id, ctx.strings) )?; } Hhbc::SelfCls(_) => { write!(w, "self")?; } Hhbc::SetG([target, value], _) => { write!( w, "set_global {}, {}", FmtVid(func, target, verbose, strings), FmtVid(func, value, verbose, strings), )?; } Hhbc::SetImplicitContextByValue(vid, _) => { write!( w, "set_implicit_context_by_value {}", FmtVid(func, vid, verbose, strings) )?; } Hhbc::SetL(vid, lid, _) => { write!( w, "set_local {}, {}", FmtLid(lid, ctx.strings), FmtVid(func, vid, verbose, strings), )?; } Hhbc::SetOpL(vid, lid, op, _) => { write!( w, "set_op_local {} {} {}", FmtLid(lid, ctx.strings), FmtSetOpOp(op), FmtVid(func, vid, verbose, strings) )?; } Hhbc::SetOpG([x, y], op, _) => { write!( w, "set_op_global {} {} {}", FmtVid(func, x, verbose, strings), FmtSetOpOp(op), FmtVid(func, y, verbose, strings) )?; } Hhbc::SetOpS(vids, op, _) => { write!( w, "set_op_static_property {}, {}, {}, {}", FmtVid(func, vids[0], verbose, strings), FmtVid(func, vids[1], verbose, strings), FmtVid(func, vids[2], verbose, strings), FmtSetOpOp(op), )?; } Hhbc::SetS(vids, readonly, _) => { write!( w, "set_s {}->{} {} = {}", FmtVid(func, vids[1], verbose, strings), FmtVid(func, vids[0], verbose, strings), FmtReadonly(readonly), FmtVid(func, vids[2], verbose, strings) )?; } Hhbc::Silence(lid, op, _) => { let lid = FmtLid(lid, ctx.strings); let op = match op { SilenceOp::Start => "start", SilenceOp::End => "end", _ => unreachable!(), }; write!(w, "silence {}, {}", lid, op)?; } Hhbc::This(_) => { write!(w, "this")?; } Hhbc::ThrowNonExhaustiveSwitch(_) => { write!(w, "throw_nonexhaustive_switch")?; } Hhbc::UnsetG(vid, _) => { write!(w, "unset {}", FmtVid(func, vid, verbose, strings))?; } Hhbc::UnsetL(lid, _) => { write!(w, "unset {}", FmtLid(lid, ctx.strings))?; } Hhbc::VerifyImplicitContextState(_) => { write!(w, "verify_implicit_context_state")?; } Hhbc::VerifyOutType(vid, lid, _) => { write!( w, "verify_out_type {}, {}", FmtVid(func, vid, verbose, strings), FmtLid(lid, ctx.strings), )?; } Hhbc::VerifyParamType(vid, lid, _) => { write!( w, "verify_param_type {}, {}", FmtVid(func, vid, verbose, strings), FmtLid(lid, ctx.strings), )?; } Hhbc::VerifyParamTypeTS(vid, lid, _) => { write!( w, "verify_param_type_ts {}, {}", FmtVid(func, vid, verbose, strings), FmtLid(lid, ctx.strings), )?; } Hhbc::VerifyRetTypeC(op, _) => { write!( w, "verify_ret_type_c {}", FmtVid(func, op, verbose, strings) )?; } Hhbc::VerifyRetTypeTS(ops, _) => { write!( w, "verify_ret_type_ts {}, {}", FmtVid(func, ops[0], verbose, strings), FmtVid(func, ops[1], verbose, strings) )?; } Hhbc::WHResult(vid, _) => { write!(w, "wh_result {}", FmtVid(func, vid, verbose, strings))?; } Hhbc::Yield(vid, _) => write!(w, "yield {}", FmtVid(func, vid, verbose, strings))?, Hhbc::YieldK(ops, _) => write!( w, "yield {} => {}", FmtVid(func, ops[0], verbose, strings), FmtVid(func, ops[1], verbose, strings) )?, } Ok(()) } fn print_hack_constant(w: &mut dyn Write, c: &HackConstant, strings: &StringInterner) -> Result { let attr = FmtAttr(c.attrs, AttrContext::Constant); write!( w, "constant {attr} {name}", name = FmtIdentifierId(c.name.id, strings) )?; if let Some(value) = &c.value { write!(w, " = {}", FmtTypedValue(value, strings))?; } writeln!(w)?; Ok(()) } fn print_include_eval( w: &mut dyn Write, ctx: &FuncContext<'_>, func: &Func<'_>, ie: &instr::IncludeEval, ) -> Result { let vid = FmtVid(func, ie.vid, ctx.verbose, ctx.strings); let kind = match ie.kind { IncludeKind::Eval => "eval", IncludeKind::Include => "include", IncludeKind::IncludeOnce => "include_once", IncludeKind::Require => "require", IncludeKind::RequireOnce => "require_once", IncludeKind::RequireOnceDoc => "require_once_doc", }; write!(w, "{} {}", kind, vid) } pub(crate) fn print_instr( w: &mut dyn Write, ctx: &mut FuncContext<'_>, func: &Func<'_>, iid: InstrId, instr: &Instr, ) -> std::result::Result<bool, Error> { // Special cases if !ctx.verbose && matches!(instr, Instr::Special(Special::Param)) { return Ok(false); } print_loc(w, ctx, func, instr.loc_id())?; write!(w, " ")?; if ctx.live_instrs.contains(&iid) { write!(w, "{} = ", FmtRawVid(ValueId::from_instr(iid)))?; } match instr { Instr::Call(call) => print_call(w, ctx, func, call)?, Instr::Hhbc(hhbc) => print_hhbc(w, ctx, func, hhbc)?, Instr::MemberOp(op) => print_member_op(w, ctx, func, op)?, Instr::Special(Special::Copy(vid)) => { write!(w, "copy {}", FmtVid(func, *vid, ctx.verbose, ctx.strings))?; } Instr::Special(Special::IrToBc(ir_to_bc)) => { print_ir_to_bc(w, ctx, func, ir_to_bc)?; } Instr::Special(Special::Textual(textual)) => print_textual(w, ctx, func, textual)?, Instr::Special(Special::Tmp(Tmp::GetVar(var))) => { write!(w, "get_var &{}", var.as_usize())?; } Instr::Special(Special::Tmp(Tmp::SetVar(var, value))) => { write!( w, "set_var &{}, {}", var.as_usize(), FmtVid(func, *value, ctx.verbose, ctx.strings) )?; } Instr::Special(Special::Param) => write!(w, "param")?, Instr::Special(Special::Select(vid, index)) => write!( w, "select {} from {}", index, FmtVid(func, *vid, ctx.verbose, ctx.strings) )?, Instr::Special(Special::Tombstone) => write!(w, "tombstone")?, Instr::Terminator(t) => print_terminator(w, ctx, func, iid, t)?, } Ok(true) } pub(crate) fn print_textual( w: &mut dyn Write, ctx: &mut FuncContext<'_>, func: &Func<'_>, textual: &instr::Textual, ) -> std::result::Result<(), Error> { use instr::Textual; let verbose = ctx.verbose; let strings = ctx.strings; match textual { Textual::AssertFalse(vid, _) => { write!( w, "textual::assert_false {}", FmtVid(func, *vid, verbose, strings) )?; } Textual::AssertTrue(vid, _) => { write!( w, "textual::assert_true {}", FmtVid(func, *vid, verbose, strings) )?; } Textual::Deref(lid) => { write!(w, "textual::deref {}", FmtLid(*lid, ctx.strings),)?; } Textual::HackBuiltin { values, target, loc: _, } => { write!(w, "textual::hack_builtin({target}")?; for vid in values.iter() { write!(w, ", {}", FmtVid(func, *vid, verbose, strings))? } write!(w, ")")?; } Textual::LoadGlobal { id, is_const } => { write!( w, "textual::load_global({}, {is_const})", FmtIdentifierId(id.id, strings) )?; } Textual::String(s) => { write!(w, "textual::string({:?})", s)?; } } Ok(()) } pub(crate) fn print_ir_to_bc( w: &mut dyn Write, ctx: &mut FuncContext<'_>, func: &Func<'_>, ir_to_bc: &IrToBc, ) -> std::result::Result<(), Error> { match ir_to_bc { IrToBc::PopC => write!(w, "popc")?, IrToBc::PopL(lid) => write!(w, "pop_local {}", FmtLid(*lid, ctx.strings),)?, IrToBc::PushL(lid) => { write!(w, "push {}", FmtLid(*lid, ctx.strings))?; } IrToBc::PushConstant(vid) => { write!(w, "push {}", FmtVid(func, *vid, ctx.verbose, ctx.strings))? } IrToBc::PushUninit => write!(w, "push_uninit")?, IrToBc::UnsetL(lid) => { write!(w, "unset_local {}", FmtLid(*lid, ctx.strings))?; } } Ok(()) } fn print_inner_loc( w: &mut dyn Write, ctx: &mut FuncContext<'_>, func: &Func<'_>, loc_id: LocId, ) -> Result { if ctx.cur_loc_id != loc_id { ctx.cur_loc_id = loc_id; if let Some(loc) = func.get_loc(loc_id) { write!(w, "<srcloc {}> ", FmtLoc(loc))?; } } Ok(()) } fn print_loc( w: &mut dyn Write, ctx: &mut FuncContext<'_>, func: &Func<'_>, loc_id: LocId, ) -> Result { if ctx.cur_loc_id != loc_id { if let Some(loc) = func.get_loc(loc_id) { let old_filename = func .get_loc(ctx.cur_loc_id) .map_or(UnitBytesId::NONE, |loc| loc.filename.0); if old_filename != loc.filename.0 { writeln!(w, " .srcloc {}", FmtFullLoc(loc, ctx.strings))?; } else { writeln!(w, " .srcloc {}", FmtLoc(loc))?; } } ctx.cur_loc_id = loc_id; } Ok(()) } fn print_member_op( w: &mut dyn Write, ctx: &mut FuncContext<'_>, func: &Func<'_>, op: &instr::MemberOp, ) -> Result { let final_op_str = match op.final_op { FinalOp::IncDecM { .. } => "incdecm", FinalOp::QueryM { .. } => "querym", FinalOp::SetM { .. } => "setm", FinalOp::SetOpM { .. } => "setopm", FinalOp::SetRangeM { .. } => "setrangem", FinalOp::UnsetM { .. } => "unsetm", }; write!(w, "{} ", final_op_str)?; let verbose = ctx.verbose; let strings = ctx.strings; let mut operands = op.operands.iter().copied(); let mut locals = op.locals.iter().copied(); match op.final_op { FinalOp::IncDecM { inc_dec_op, .. } => match inc_dec_op { IncDecOp::PreInc => write!(w, "++")?, IncDecOp::PreDec => write!(w, "--")?, IncDecOp::PostInc | IncDecOp::PostDec => {} _ => unreachable!(), }, FinalOp::QueryM { .. } | FinalOp::SetM { .. } | FinalOp::SetOpM { .. } | FinalOp::SetRangeM { .. } | FinalOp::UnsetM { .. } => {} } match op.base_op { BaseOp::BaseC { mode, .. } => { if mode != MOpMode::None { write!(w, "{} ", FmtMOpMode(mode))?; } let vid = operands.next().unwrap(); write!(w, "{}", FmtVid(func, vid, true, strings))?; } BaseOp::BaseGC { mode, .. } => { if mode != MOpMode::None { write!(w, "{} ", FmtMOpMode(mode))?; } let vid = operands.next().unwrap(); write!(w, "global {}", FmtVid(func, vid, verbose, strings))?; } BaseOp::BaseH { .. } => { write!(w, "$this")?; } BaseOp::BaseL { mode, readonly, .. } => { if mode != MOpMode::None { write!(w, "{} ", FmtMOpMode(mode))?; } if readonly != ReadonlyOp::Any { write!(w, "{} ", FmtReadonly(readonly))?; } let lid = locals.next().unwrap(); write!(w, "{}", FmtLid(lid, ctx.strings))?; } BaseOp::BaseSC { mode, readonly, .. } => { if mode != MOpMode::None { write!(w, "{} ", FmtMOpMode(mode))?; } if readonly != ReadonlyOp::Any { write!(w, "{} ", FmtReadonly(readonly))?; } let prop = operands.next().unwrap(); let cls = operands.next().unwrap(); write!( w, "{}::{}", FmtVid(func, cls, true, strings), FmtVid(func, prop, verbose, strings) )?; } BaseOp::BaseST { mode, readonly, prop, .. } => { if mode != MOpMode::None { write!(w, "{} ", FmtMOpMode(mode))?; } if readonly != ReadonlyOp::Any { write!(w, "{} ", FmtReadonly(readonly))?; } let cls = operands.next().unwrap(); write!( w, "{}::{}", FmtVid(func, cls, true, strings), FmtQuotedStringId(prop.id, strings) )?; } } for op in op.intermediate_ops.iter() { print_member_key( w, ctx, &mut operands, &mut locals, func, op.loc, op.mode, op.readonly, &op.key, )?; } match op.final_op { FinalOp::IncDecM { ref key, readonly, loc, .. } | FinalOp::QueryM { ref key, readonly, loc, .. } | FinalOp::SetM { ref key, readonly, loc, .. } | FinalOp::SetOpM { ref key, readonly, loc, .. } | FinalOp::UnsetM { ref key, readonly, loc, .. } => { print_member_key( w, ctx, &mut operands, &mut locals, func, loc, MOpMode::None, readonly, key, )?; } FinalOp::SetRangeM { sz, set_range_op, .. } => { let s1 = operands.next().unwrap(); let s2 = operands.next().unwrap(); let s3 = operands.next().unwrap(); let set_range_op = match set_range_op { SetRangeOp::Forward => "forward", SetRangeOp::Reverse => "reverse", _ => unreachable!(), }; write!( w, " set {}, {}, {} size {} {}", FmtVid(func, s1, verbose, strings), FmtVid(func, s2, verbose, strings), FmtVid(func, s3, verbose, strings), sz, set_range_op )?; } } match op.final_op { FinalOp::IncDecM { inc_dec_op, .. } => match inc_dec_op { IncDecOp::PreInc | IncDecOp::PreDec => {} IncDecOp::PostInc => write!(w, " ++")?, IncDecOp::PostDec => write!(w, " --")?, _ => unreachable!(), }, FinalOp::QueryM { query_m_op, .. } => match query_m_op { QueryMOp::CGet => {} QueryMOp::CGetQuiet => write!(w, " quiet")?, QueryMOp::Isset => write!(w, " isset")?, QueryMOp::InOut => write!(w, " inout")?, _ => unreachable!(), }, FinalOp::SetM { .. } => { let vid = operands.next().unwrap(); write!(w, " = {}", FmtVid(func, vid, verbose, strings))?; } FinalOp::SetOpM { set_op_op, .. } => { let vid = operands.next().unwrap(); write!( w, " {} {}", FmtSetOpOp(set_op_op), FmtVid(func, vid, verbose, strings) )?; } FinalOp::SetRangeM { .. } | FinalOp::UnsetM { .. } => {} } assert_eq!(operands.next(), None); Ok(()) } fn print_member_key( w: &mut dyn Write, ctx: &mut FuncContext<'_>, operands: &mut impl Iterator<Item = ValueId>, locals: &mut impl Iterator<Item = LocalId>, func: &Func<'_>, loc: LocId, mode: MOpMode, readonly: ReadonlyOp, key: &MemberKey, ) -> Result { let verbose = ctx.verbose; let strings = ctx.strings; match *key { MemberKey::EC | MemberKey::EI(_) | MemberKey::EL | MemberKey::ET(_) | MemberKey::W => { w.write_str("[")? } MemberKey::PC | MemberKey::PL | MemberKey::PT(_) => w.write_str("->")?, MemberKey::QT(_) => w.write_str("?->")?, } print_inner_loc(w, ctx, func, loc)?; if mode != MOpMode::None { write!(w, " {} ", FmtMOpMode(mode))?; } if readonly != ReadonlyOp::Any { write!(w, " {} ", FmtReadonly(readonly))?; } match *key { MemberKey::EC => { let vid = operands.next().unwrap(); write!(w, "{}]", FmtVid(func, vid, verbose, strings))?; } MemberKey::EI(i) => write!(w, "{}]", i)?, MemberKey::EL => { let lid = locals.next().unwrap(); write!(w, "{}]", FmtLid(lid, strings))? } MemberKey::ET(sid) => write!(w, "{}]", FmtQuotedStringId(sid, strings))?, MemberKey::PC => { let vid = operands.next().unwrap(); write!(w, "{}", FmtVid(func, vid, verbose, strings))?; } MemberKey::PL => { let lid = locals.next().unwrap(); write!(w, "{}", FmtLid(lid, strings))? } MemberKey::PT(pid) => write!(w, "{}", FmtQuotedStringId(pid.id, strings))?, MemberKey::QT(pid) => write!(w, "{}", FmtQuotedStringId(pid.id, strings))?, MemberKey::W => write!(w, "]")?, } Ok(()) } fn print_method( w: &mut dyn Write, clsid: ClassId, method: &Method<'_>, verbose: bool, strings: &StringInterner, ) -> Result { print_top_level_loc(w, method.func.get_loc(method.func.loc_id), strings)?; writeln!( w, "method {clsid}::{method}{tparams}{params}{shadowed_tparams}: {ret_type} {attr} {vis} {{", clsid = FmtIdentifierId(clsid.id, strings), method = FmtIdentifierId(method.name.id, strings), tparams = FmtTParams(&method.func.tparams, strings), shadowed_tparams = FmtShadowedTParams(&method.func.shadowed_tparams, strings), params = FmtFuncParams(&method.func, strings), ret_type = FmtTypeInfo(&method.func.return_type, strings), vis = FmtVisibility(method.visibility), attr = FmtAttr(method.attrs, AttrContext::Method), )?; print_method_flags(w, method.flags)?; print_attributes(w, &method.attributes, strings)?; print_coeffects(w, &method.coeffects)?; print_func_body(w, &method.func, verbose, strings, None, None)?; writeln!(w, "}}")?; writeln!(w) } fn print_method_flags(w: &mut dyn Write, mut flags: MethodFlags) -> Result { [ get_bit(&mut flags, MethodFlags::IS_ASYNC, ".async"), get_bit(&mut flags, MethodFlags::IS_GENERATOR, ".generator"), get_bit( &mut flags, MethodFlags::IS_PAIR_GENERATOR, ".pair_generator", ), get_bit(&mut flags, MethodFlags::IS_CLOSURE_BODY, ".closure_body"), ] .into_iter() .flatten() .try_for_each(|f| writeln!(w, " {f}")) } fn incdec_what(op: IncDecOp) -> (&'static str, &'static str) { let what = match op { IncDecOp::PreInc | IncDecOp::PostInc => "++", IncDecOp::PreDec | IncDecOp::PostDec => "--", _ => panic!("bad IncDecOp value"), }; match op { IncDecOp::PreInc | IncDecOp::PreDec => (what, ""), IncDecOp::PostInc | IncDecOp::PostDec => ("", what), _ => panic!("bad IncDecOp value"), } } pub(crate) fn print_param( w: &mut dyn Write, strings: &StringInterner, func: &Func<'_>, param: &Param<'_>, ) -> Result { let Param { is_inout, is_readonly, is_variadic, ref ty, name, default_value, ref user_attributes, } = *param; if is_inout { write!(w, "inout ")?; } if is_readonly { write!(w, "readonly ")?; } if !user_attributes.is_empty() { write!( w, "[{}] ", FmtSep::comma(user_attributes.iter(), |w, a| FmtAttribute(a, strings) .fmt(w)) )?; } let ellipsis_for_variadic = if is_variadic { "..." } else { "" }; write!( w, "{} {}{}", FmtTypeInfo(ty, strings), ellipsis_for_variadic, FmtIdentifierId(name, strings) )?; if let Some(dv) = default_value { write!( w, " @ {} ({})", FmtBid(func, dv.init, false), FmtQuotedStr(&dv.expr) )?; } Ok(()) } fn print_property(w: &mut dyn Write, property: &Property<'_>, strings: &StringInterner) -> Result { write!( w, " property {name} {flags}{attributes} {vis} : {ty} {doc}", name = FmtIdentifierId(property.name.id, strings), flags = FmtAttr(property.flags, AttrContext::Property), attributes = FmtSep::new(" <", ", ", ">", property.attributes.iter(), |w, attr| { write!( w, "{}({})", FmtIdentifierId(attr.name.id, strings), FmtSep::comma(attr.arguments.iter(), |w, arg| { FmtTypedValue(arg, strings).fmt(w) }) ) }), vis = FmtVisibility(property.visibility), ty = FmtTypeInfo(&property.type_info, strings), doc = FmtDocComment(property.doc_comment.as_ref().into()), )?; if let Some(iv) = property.initial_value.as_ref() { write!(w, " = {}", FmtTypedValue(iv, strings))?; } writeln!(w) } fn print_symbol_refs(w: &mut dyn Write, refs: &SymbolRefs<'_>) -> Result { let SymbolRefs { classes, constants, functions, includes, } = refs; for v in classes { writeln!(w, ".class_ref {}", FmtIdentifier(v.as_bytes()))?; } for v in constants { writeln!(w, ".const_ref {}", FmtIdentifier(v.as_bytes()))?; } for v in functions { writeln!(w, ".func_ref {}", FmtIdentifier(v.as_bytes()))?; } for v in includes { write!(w, ".include_ref ")?; match v { IncludePath::Absolute(path) => write!(w, "{}", FmtQuotedStr(path))?, IncludePath::SearchPathRelative(path) => write!(w, "relative {}", FmtQuotedStr(path))?, IncludePath::IncludeRootRelative(root, path) => { write!(w, "rooted {} {}", FmtQuotedStr(root), FmtQuotedStr(path))? } IncludePath::DocRootRelative(path) => write!(w, "doc {}", FmtQuotedStr(path))?, } writeln!(w)?; } Ok(()) } fn print_terminator( w: &mut dyn Write, ctx: &mut FuncContext<'_>, func: &Func<'_>, _iid: InstrId, terminator: &Terminator, ) -> Result { let verbose = ctx.verbose; let strings = ctx.strings; match terminator { Terminator::CallAsync(call, targets) => print_call_async(w, ctx, func, call, targets)?, Terminator::Enter(bid, _) => write!(w, "enter to {}", FmtBid(func, *bid, verbose),)?, Terminator::Exit(vid, _) => { write!(w, "exit {}", FmtVid(func, *vid, verbose, strings))?; } Terminator::Fatal(vid, op, _) => { let op = match *op { ir_core::FatalOp::Parse => "parse", ir_core::FatalOp::Runtime => "runtime", ir_core::FatalOp::RuntimeOmitFrame => "runtime_omit_frame", _ => panic!("bad FatalOp value"), }; write!(w, "fatal {}, {}", op, FmtVid(func, *vid, verbose, strings))? } Terminator::IterInit(args, vid) => { write!( w, "iterator ^{} init from {} jmp to {} else {} with {}", args.iter_id.idx, FmtVid(func, *vid, verbose, strings), FmtBid(func, args.targets[0], verbose), FmtBid(func, args.targets[1], verbose), FmtOptKeyValue(args.key_lid(), args.value_lid(), strings) )?; } Terminator::IterNext(args) => { write!( w, "iterator ^{} next jmp to {} else {} with {}", args.iter_id.idx, FmtBid(func, args.targets[0], verbose), FmtBid(func, args.targets[1], verbose), FmtOptKeyValue(args.key_lid(), args.value_lid(), strings) )?; } Terminator::Jmp(bid, _) => write!(w, "jmp to {}", FmtBid(func, *bid, verbose),)?, Terminator::JmpArgs(bid, vids, _) => write!( w, "jmp to {} with ({})", FmtBid(func, *bid, verbose), FmtSep::comma(vids.iter(), |w, vid| FmtVid(func, *vid, verbose, strings) .fmt(w)) )?, Terminator::JmpOp { cond, pred, targets, loc: _, } => { let pred = match pred { Predicate::NonZero => "jmp if nonzero", Predicate::Zero => "jmp if zero", }; write!( w, "{} {} to {} else {}", pred, FmtVid(func, *cond, verbose, strings), FmtBid(func, targets[0], verbose), FmtBid(func, targets[1], verbose), )?; } Terminator::MemoGet(get) => { write!( w, "memo_get {} to {} else {}", FmtLids(&get.locals, strings), FmtBid(func, get.value_edge(), verbose), FmtBid(func, get.no_value_edge(), verbose) )?; } Terminator::MemoGetEager(get) => { write!( w, "memo_get_eager {} to {} eager {} else {}", FmtLids(&get.locals, strings), FmtBid(func, get.suspended_edge(), verbose), FmtBid(func, get.eager_edge(), verbose), FmtBid(func, get.no_value_edge(), verbose) )?; } Terminator::NativeImpl(_) => { write!(w, "native_impl")?; } Terminator::Ret(vid, _) => { write!(w, "ret {}", FmtVid(func, *vid, verbose, strings))?; } Terminator::RetCSuspended(vid, _) => { write!( w, "ret_c_suspended {}", FmtVid(func, *vid, verbose, strings) )?; } Terminator::RetM(vids, _) => { write!( w, "ret [{}]", FmtSep::comma(vids.iter(), |w, vid| FmtVid(func, *vid, verbose, strings) .fmt(w)) )?; } Terminator::Switch { cond, bounded, base, targets, loc: _, } => { let bounded = match *bounded { SwitchKind::Bounded => "bounded", SwitchKind::Unbounded => "unbounded", _ => unreachable!(), }; write!( w, "switch {} {} {base} [{}]", bounded, FmtVid(func, *cond, verbose, strings), FmtSep::comma(targets.iter(), |w, target| { write!(w, "{}", FmtBid(func, *target, verbose),) }) )?; } Terminator::SSwitch { cond, cases, targets, .. } => { write!( w, "sswitch {} [{}]", FmtVid(func, *cond, verbose, strings), FmtSep::comma(cases.iter().zip(targets.iter()), |w, (case, target)| { write!( w, "{} => {}", FmtQuotedStringId(*case, strings), FmtBid(func, *target, verbose), ) }) )?; } Terminator::Throw(vid, _) => { write!(w, "throw {}", FmtVid(func, *vid, verbose, strings))?; } Terminator::ThrowAsTypeStructException(ops, _) => { write!( w, "throw_as_type_struct_exception {}, {}", FmtVid(func, ops[0], verbose, strings), FmtVid(func, ops[1], verbose, strings) )?; } Terminator::Unreachable => write!(w, "unreachable")?, } Ok(()) } fn print_type_constant( w: &mut dyn Write, tc: &TypeConstant<'_>, strings: &StringInterner, ) -> Result { write!(w, " type_constant ")?; if tc.is_abstract { write!(w, "abstract ")?; } write!(w, "{}", FmtIdentifier(&tc.name))?; if let Some(init) = &tc.initializer { write!(w, " = {}", FmtTypedValue(init, strings))?; } writeln!(w) } fn print_typedef(w: &mut dyn Write, typedef: &Typedef, strings: &StringInterner) -> Result { let Typedef { attributes, attrs, loc, name, type_info_union, type_structure, case_type, } = typedef; print_top_level_loc(w, Some(loc), strings)?; writeln!( w, "typedef {vis} {name}: {ty} = {attributes}{ts} {attrs}", vis = if *case_type { "case_type" } else { "alias" }, name = FmtIdentifierId(name.id, strings), ty = FmtSep::comma(type_info_union.iter(), |w, ti| FmtTypeInfo(ti, strings) .fmt(w)), attributes = FmtSep::new("<", ",", "> ", attributes, |w, attribute| FmtAttribute( attribute, strings ) .fmt(w)), ts = FmtTypedValue(type_structure, strings), attrs = FmtAttr(*attrs, AttrContext::Typedef) ) } pub fn print_unit(w: &mut dyn Write, unit: &Unit<'_>, verbose: bool) -> Result { let strings = &unit.strings; for attr in &unit.file_attributes { writeln!(w, "attribute {}", FmtAttribute(attr, strings))?; } if !unit.modules.is_empty() { for module in unit.modules.iter() { let Module { attributes, name, src_loc, doc_comment, } = module; print_top_level_loc(w, Some(src_loc), strings)?; write!( w, "module {name} [{attributes}] ", name = FmtIdentifierId(name.id, strings), attributes = FmtSep::comma(attributes.iter(), |w, a| FmtAttribute(a, strings).fmt(w)) )?; if let Some(doc_comment) = doc_comment { write!(w, "{}", FmtEscapedString(doc_comment))?; } else { write!(w, "N")?; } writeln!(w)?; } writeln!(w)?; } if let Some(module_use) = unit.module_use.as_ref() { writeln!(w, "module_use {}\n", FmtEscapedString(module_use))?; } for c in &unit.constants { print_hack_constant(w, c, strings)?; } if !unit.typedefs.is_empty() { for typedef in &unit.typedefs { print_typedef(w, typedef, strings)?; } writeln!(w)?; } for c in &unit.classes { print_class(w, c, strings)?; } for f in &unit.functions { print_function(w, f, verbose, strings)?; } for c in &unit.classes { for m in &c.methods { print_method(w, c.name, m, verbose, strings)?; } } print_fatal(w, unit.fatal.as_ref(), strings)?; print_symbol_refs(w, &unit.symbol_refs)?; Ok(()) }
Rust
hhvm/hphp/hack/src/hackc/ir/print/util.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. //! Print utility functions. use std::cell::Cell; use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Result; use ir_core::instr::HasOperands; use ir_core::Func; use ir_core::InstrIdSet; use ir_core::ValueId; /// Display the iterator by calling the helper to display each value separated /// by commas. pub struct FmtSep<'a, T, I, F>(&'a str, &'a str, &'a str, Cell<Option<I>>, F) where I: Iterator<Item = T>, F: Fn(&mut Formatter<'_>, T) -> Result; impl<'a, T, I, F> FmtSep<'a, T, I, F> where I: Iterator<Item = T>, F: Fn(&mut Formatter<'_>, T) -> Result, { /// Create a new FmtSep. Note that the difference between: /// /// format!("({})", FmtSep::new("", ", ", "", ...)) /// /// and /// /// format!("{}", FmtSep::new("(", ", ", ")", ...)) /// /// is that in the first example the parentheses are always printed and in /// the second they're only printed if the iter is non-empty. /// pub fn new( prefix: &'a str, infix: &'a str, postfix: &'a str, iter: impl IntoIterator<Item = T, IntoIter = I>, f: F, ) -> Self { let iter2 = iter.into_iter(); Self(prefix, infix, postfix, Cell::new(Some(iter2)), f) } pub fn comma(iter: impl IntoIterator<Item = T, IntoIter = I>, f: F) -> Self { let iter2 = iter.into_iter(); Self("", ", ", "", Cell::new(Some(iter2)), f) } } impl<T, I, F> Display for FmtSep<'_, T, I, F> where I: Iterator<Item = T>, F: Fn(&mut Formatter<'_>, T) -> Result, { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let FmtSep(prefix, infix, postfix, iter, callback) = self; let mut iter = iter.take().unwrap(); if let Some(e) = iter.next() { f.write_str(prefix)?; callback(f, e)?; for e in iter { f.write_str(infix)?; callback(f, e)?; } f.write_str(postfix)?; } Ok(()) } } /// If self.0 is Some(_) then call F with the non-None value. pub struct FmtOption<T, F>(pub Option<T>, pub F) where F: Fn(&mut Formatter<'_>, &T) -> Result; impl<T, F: Fn(&mut Formatter<'_>, &T) -> Result> Display for FmtOption<T, F> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { if let Some(value) = self.0.as_ref() { self.1(f, value) } else { Ok(()) } } } /// If self.0 is Some(_) then call F1 with the non-None value otherwise call F2. pub struct FmtOptionOr<T, F1, F2>(pub Option<T>, pub F1, pub F2) where F1: Fn(&mut Formatter<'_>, &T) -> Result, F2: Fn(&mut Formatter<'_>) -> Result; impl<T, F1, F2> Display for FmtOptionOr<T, F1, F2> where F1: Fn(&mut Formatter<'_>, &T) -> Result, F2: Fn(&mut Formatter<'_>) -> Result, { fn fmt(&self, f: &mut Formatter<'_>) -> Result { if let Some(value) = self.0.as_ref() { self.1(f, value) } else { self.2(f) } } } /// Display a ByteVec as an escaped quoted string. pub struct FmtEscapedString<'a>(pub &'a [u8]); impl Display for FmtEscapedString<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let mut s = String::with_capacity(self.0.len() * 2 + 2); s.push('"'); for &c in self.0 { match c { b'\\' => s.push_str("\\\\"), b'\n' => s.push_str("\\n"), b'\r' => s.push_str("\\r"), b'\t' => s.push_str("\\t"), b'\"' => s.push_str("\\\""), c if c.is_ascii_graphic() || c == b' ' => s.push(c as char), c => s.push_str(&format!("\\x{:02x}", c)), } } s.push('"'); f.write_str(&s) } } /// Return a set of live InstrIds, used to decide which printed instructions /// need to print their SSA variable names. pub(crate) fn compute_live_instrs(func: &Func<'_>, verbose: bool) -> InstrIdSet { if verbose { return func.body_iids().collect(); } func.body_instrs() .flat_map(|instr| instr.operands().iter().copied()) .filter_map(ValueId::instr) .collect() }
TOML
hhvm/hphp/hack/src/hackc/ir/testutils/Cargo.toml
# @generated by autocargo [package] name = "testutils" version = "0.0.0" edition = "2021" [lib] path = "lib.rs" [dependencies] hash = { version = "0.0.0", path = "../../../utils/hash" } ir_core = { version = "0.0.0", path = "../ir_core" } print = { version = "0.0.0", path = "../print" }
Rust
hhvm/hphp/hack/src/hackc/ir/testutils/lib.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. pub mod testutils; pub use testutils::*;
Rust
hhvm/hphp/hack/src/hackc/ir/testutils/testutils.rs
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. //! This module contains shared functions for use by tests. use std::sync::Arc; use hash::HashMap; use hash::HashSet; use ir_core::constant::Constant; use ir_core::instr; use ir_core::BlockId; use ir_core::Func; use ir_core::FuncBuilder; use ir_core::FunctionId; use ir_core::HasEdges; use ir_core::Instr; use ir_core::LocId; use ir_core::StringInterner; use ir_core::ValueId; /// Given a simple CFG description, create a Func that matches it. pub fn build_test_func<'a>(testcase: &[Block]) -> (Func<'a>, Arc<StringInterner>) { let strings = Arc::new(StringInterner::default()); let func = build_test_func_with_strings(testcase, Arc::clone(&strings)); (func, strings) } pub fn build_test_func_with_strings<'a>( testcase: &[Block], strings: Arc<StringInterner>, ) -> Func<'a> { // Create a function whose CFG matches testcase. FuncBuilder::build_func(strings, |fb| { let mut name_to_bid = HashMap::with_capacity_and_hasher(testcase.len(), Default::default()); let mut name_to_vid = HashMap::default(); for (i, block) in testcase.iter().enumerate() { let bid = if i == 0 { Func::ENTRY_BID } else { fb.alloc_bid() }; name_to_bid.insert(block.name.clone(), bid); fb.start_block(bid); for pn in &block.params { let pid = fb.alloc_param(); name_to_vid.insert(pn.clone(), pid); } } for block in testcase { fb.start_block(name_to_bid[&block.name]); block.emit(fb, &name_to_bid, &mut name_to_vid); } }) } #[derive(Debug, Clone)] pub struct Block { /// The name of the block for test lookup purposes. pub name: String, /// The pname of the block. pub pname: Option<String>, /// For each "call_target" we create a simple call instruction calling a /// function with that target name. pub call_targets: Vec<(String, Option<String>)>, /// What kind of terminator to use on this block. pub terminator: Terminator, /// The parameters this block expects. pub params: Vec<String>, } #[derive(Debug, Clone)] pub enum Terminator { Ret, RetValue(String), Jmp(String), JmpArg(String, String), JmpOp(String, String), CallAsync { target: String, lazy: String, eager: String, }, } impl Block { pub fn successors(&self) -> impl Iterator<Item = &String> { match &self.terminator { Terminator::Ret | Terminator::RetValue(_) => vec![].into_iter(), Terminator::Jmp(target) | Terminator::JmpArg(target, _) => vec![target].into_iter(), Terminator::JmpOp(a, b) => vec![a, b].into_iter(), Terminator::CallAsync { lazy, eager, .. } => vec![lazy, eager].into_iter(), } } fn emit( &self, fb: &mut FuncBuilder<'_>, name_to_bid: &HashMap<String, BlockId>, name_to_vid: &mut HashMap<String, ValueId>, ) { if let Some(pname) = self.pname.as_ref() { fb.cur_block_mut().pname_hint = Some(pname.to_string()); } let bid_for = |name: &str| -> BlockId { *name_to_bid.get(name).unwrap() }; let loc = LocId::NONE; for (target, name) in &self.call_targets { let target = FunctionId::from_str(target, &fb.strings); let iid = fb.emit(Instr::simple_call(target, &[], loc)); if let Some(name) = name { name_to_vid.insert(name.clone(), iid); } } let null_iid = fb.emit_constant(Constant::Null); let terminator = match &self.terminator { Terminator::Ret => Instr::ret(null_iid, loc), Terminator::RetValue(arg) => { let arg = *name_to_vid.get(arg).unwrap(); Instr::ret(arg, loc) } Terminator::Jmp(a) => { let a = bid_for(a); Instr::jmp(a, loc) } Terminator::JmpArg(a, arg) => { let a = bid_for(a); let arg = *name_to_vid.get(arg).unwrap(); Instr::jmp_args(a, &[arg], loc) } Terminator::JmpOp(a, b) => { let a = bid_for(a); let b = bid_for(b); Instr::jmp_op(null_iid, instr::Predicate::NonZero, a, b, loc) } Terminator::CallAsync { target, lazy, eager, } => { let lazy = bid_for(lazy); let eager = bid_for(eager); let func = FunctionId::from_str(target, &fb.strings); let call = ir_core::Call { operands: Box::new([]), context: ir_core::UnitBytesId::NONE, detail: instr::CallDetail::FCallFuncD { func }, flags: ir_core::FCallArgsFlags::default(), num_rets: 1, inouts: None, readonly: None, loc, }; Instr::Terminator(instr::Terminator::CallAsync(Box::new(call), [lazy, eager])) } }; fb.emit(terminator); } /// A simple block which jumps to a single successor. pub fn jmp(name: &str, successor: &str) -> Block { Self::ret(name).with_terminator(Terminator::Jmp(successor.to_string())) } /// A simple block which jumps to two successors. pub fn jmp_op(name: &str, successors: [&str; 2]) -> Block { Self::ret(name).with_terminator(Terminator::JmpOp( successors[0].to_string(), successors[1].to_string(), )) } pub fn jmp_arg(name: &str, successor: &str, value: &str) -> Block { Self::ret(name) .with_terminator(Terminator::JmpArg(successor.to_string(), value.to_string())) } pub fn ret(name: &str) -> Block { Block { call_targets: Vec::new(), name: name.to_owned(), params: Vec::new(), pname: Some(name.to_owned()), terminator: Terminator::Ret, } } pub fn ret_value(name: &str, param: &str) -> Block { Self::ret(name).with_terminator(Terminator::RetValue(param.to_owned())) } pub fn call_async(name: &str, target: &str, [lazy, eager]: [&str; 2]) -> Block { Self::ret(name).with_terminator(Terminator::CallAsync { target: target.to_owned(), lazy: lazy.to_owned(), eager: eager.to_owned(), }) } pub fn unnamed(mut self) -> Self { self.pname = None; self } pub fn with_target(mut self) -> Self { self.call_targets = vec![(format!("{}_target", self.name), None)]; self } pub fn with_named_target(mut self, name: &str) -> Self { let name = name.to_owned(); self.call_targets = vec![(format!("{}_target", self.name), Some(name))]; self } pub fn with_terminator(mut self, terminator: Terminator) -> Self { self.terminator = terminator; self } pub fn with_param(mut self, name: &str) -> Self { self.params = vec![name.to_owned()]; self } } /// Structurally compare two Funcs. pub fn assert_func_struct_eq<'a>(func_a: &Func<'a>, func_b: &Func<'a>, strings: &StringInterner) { if let Err(e) = cmp_func_struct_eq(func_a, func_b) { panic!( "Function mismatch: {}\n{}\n{}", e, print::DisplayFunc::new(func_a, true, strings), print::DisplayFunc::new(func_b, true, strings) ); } } macro_rules! cmp_eq { ($a:expr, $b:expr, $($rest:tt)+) => { if $a == $b { Ok(()) } else { Err(format!($($rest)+)) } }; } fn cmp_func_struct_eq<'a>(func_a: &Func<'a>, func_b: &Func<'a>) -> Result<(), String> { let mut block_eq: HashSet<(BlockId, BlockId)> = HashSet::default(); let mut pending_cmp: Vec<(BlockId, BlockId)> = vec![(Func::ENTRY_BID, Func::ENTRY_BID)]; cmp_eq!( func_a.params.len(), func_b.params.len(), "param length mismatch", )?; for (param_a, param_b) in func_a.params.iter().zip(func_b.params.iter()) { match ( param_a.default_value.as_ref(), param_b.default_value.as_ref(), ) { (Some(dv_a), Some(dv_b)) => { pending_cmp.push((dv_a.init, dv_b.init)); } (None, None) => {} _ => panic!("Mismatch in default value index"), } } while let Some((bid_a, bid_b)) = pending_cmp.pop() { block_eq.insert((bid_a, bid_b)); cmp_block_struct_eq(func_a, bid_a, func_b, bid_b)?; let term_a = func_a.terminator(bid_a); let term_b = func_b.terminator(bid_b); cmp_eq!( term_a.edges().len(), term_b.edges().len(), "mismatched terminator edge count", )?; for (edge_a, edge_b) in term_a.edges().iter().zip(term_b.edges().iter()) { pending_cmp.push((*edge_a, *edge_b)); } } Ok(()) } fn cmp_block_struct_eq<'a>( func_a: &Func<'a>, bid_a: BlockId, func_b: &Func<'a>, bid_b: BlockId, ) -> Result<(), String> { let block_a = func_a.block(bid_a); let block_b = func_b.block(bid_b); cmp_eq!( block_a.params.len(), block_b.params.len(), "block param len mismatch", )?; cmp_eq!( block_a.iids.len(), block_b.iids.len(), "block iids len mismatch", )?; cmp_eq!( &block_a.pname_hint, &block_b.pname_hint, "pname mismatch in ({}, {})", bid_a, bid_b )?; // TODO: check tcid for (iid_a, iid_b) in block_a .iids .iter() .copied() .zip(block_b.iids.iter().copied()) { cmp_eq!( std::mem::discriminant(func_a.instr(iid_a)), std::mem::discriminant(func_b.instr(iid_b)), "instr mismatch", )?; } Ok(()) }
TOML
hhvm/hphp/hack/src/hackc/ir/verify/Cargo.toml
# @generated by autocargo [package] name = "verify" version = "0.0.0" edition = "2021" [lib] path = "lib.rs" [dependencies] analysis = { version = "0.0.0", path = "../analysis" } ir_core = { version = "0.0.0", path = "../ir_core" } itertools = "0.10.3" print = { version = "0.0.0", path = "../print" }
Rust
hhvm/hphp/hack/src/hackc/ir/verify/lib.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. pub mod verify; pub use self::verify::*;
Rust
hhvm/hphp/hack/src/hackc/ir/verify/verify.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. //! Verifier for HackIR. This traverses the HackIR structures and makes sure //! that the required invariants still hold true. use std::collections::hash_map::Entry; use std::fmt::Display; use analysis::PredecessorFlags; use analysis::Predecessors; use ir_core::instr::HasEdges; use ir_core::instr::HasOperands; use ir_core::instr::Hhbc; use ir_core::instr::IrToBc; use ir_core::instr::Special; use ir_core::instr::Terminator; use ir_core::string_intern::StringInterner; use ir_core::Block; use ir_core::BlockId; use ir_core::BlockIdMap; use ir_core::FullInstrId; use ir_core::Func; use ir_core::Instr; use ir_core::InstrId; use ir_core::InstrIdSet; use ir_core::ValueId; use itertools::Itertools; use print::FmtBid; use print::FmtRawVid; use print::FmtVid; /// Flags controlling the details of verification. #[derive(Default)] pub struct Flags { pub allow_critical_edges: bool, } /// Asserts that a condition is true and reports if it's not. /// /// ``` /// check!(self, mycond, "mycond should be true but it's {mycond}"); /// ``` macro_rules! check { ($self:expr, $cond:expr, $($why:expr),+ $(,)? ) => {{ let pred = $cond; if (!pred) { $self.check_failed(&format!($($why),+)); } }} } /// Fail a verify. /// /// ``` /// check_failed!("mycond failed to verify with value {mycond}"); /// ``` macro_rules! check_failed { ($self:expr, $($why:expr),+ $(,)? ) => {{ $self.check_failed(&format!($($why),+)) }} } struct VerifyFunc<'a, 'b> { // Mapping of what InstrIds dominate each Block. dominated_iids: BlockIdMap<InstrIdSet>, func: &'b Func<'a>, #[allow(dead_code)] flags: &'b Flags, predecessors: Predecessors, strings: &'b StringInterner, } impl<'a, 'b> VerifyFunc<'a, 'b> { fn new(func: &'b Func<'a>, flags: &'b Flags, strings: &'b StringInterner) -> Self { // Catch unwind so we can print the function before continuing the // panic. let predecessors = std::panic::catch_unwind(|| { analysis::compute_predecessor_blocks(func, PredecessorFlags::default()) }); let predecessors = match predecessors { Ok(predecessors) => predecessors, Err(e) => { Self::report_func_error( "compute_predecessor_blocks panic'd", func, None, None, strings, ); std::panic::resume_unwind(e); } }; VerifyFunc { dominated_iids: Default::default(), func, flags, predecessors, strings, } } fn report_func_error( why: &str, func: &Func<'_>, predecessors: Option<&Predecessors>, dominated_iids: Option<&BlockIdMap<InstrIdSet>>, strings: &StringInterner, ) { eprintln!("VERIFY FAILED: {why}"); use print::FmtSep; let f_pre_block = |w: &mut dyn std::fmt::Write, bid| { if let Some(pds) = predecessors.as_ref().and_then(|p| p.get(&bid)) { writeln!( w, " Predecessor BlockIds: [{}]", FmtSep::comma(pds.iter().sorted(), |w, bid| FmtBid(func, *bid, true,) .fmt(w)) )?; } if let Some(dids) = dominated_iids.as_ref().and_then(|d| d.get(&bid)) { writeln!( w, " Dominator InstrIds: [{}]", FmtSep::comma(dids.iter().sorted(), |w, vid| FmtVid( func, (*vid).into(), true, strings ) .fmt(w)) )?; } Ok(()) }; let mut df = print::DisplayFunc::new(func, true, strings); df.f_pre_block = Some(&f_pre_block); eprintln!("{}", df); } fn check_failed(&self, why: &str) -> ! { Self::report_func_error( why, self.func, Some(&self.predecessors), Some(&self.dominated_iids), self.strings, ); panic!("VERIFY FAILED: {}", why); } fn verify_block(&mut self, bid: BlockId, block: &Block) { check!( self, block.is_terminated(self.func), "block {} is unterminated", bid ); // This requires RPO to work properly! let mut dominated_iids = std::mem::take(self.dominated_iids.entry(bid).or_default()); for &iid in &block.params { dominated_iids.insert(iid); } for &iid in &block.params { let instr = self.func.instr(iid); check!( self, instr.is_param(), "block {} param {} is not a Param", FmtBid(self.func, bid, true), iid ); } let terminator_iid = block.terminator_iid(); for (iid_idx, iid) in block.iids().enumerate() { let instr = self.func.instr(iid); // Only the last Instr should be terminal. if iid == terminator_iid { check!( self, instr.is_terminal(), "terminator iid {} in block {} is non-terminal", iid, bid ); } else { check!( self, !instr.is_terminal(), "non-terminator iid {} in block {} is terminal", iid, bid ); } self.verify_instr( block, iid, iid_idx, self.func.instr(iid), &mut dominated_iids, ); } // Push the dominated IIDs into the successors. for &edge in self.func.edges(bid) { self.push_dominated_iids(edge, &dominated_iids); } let handler = self.func.catch_target(bid); if handler != BlockId::NONE { // Push the dominated IIDs into the catch handler. self.push_dominated_iids(handler, &dominated_iids); } self.dominated_iids.insert(bid, dominated_iids); if !self.flags.allow_critical_edges { // If we have multiple successors then our successors must all have // only a single predecessor. let i = self.func.terminator(bid); let successors = i.edges(); if successors.len() > 1 { for t in successors { check!( self, self.predecessors[t].len() == 1, "Block {bid} successor {t} is a critical edge! ({bid} has {} successors, {t} has {} predecessors)", successors.len(), self.predecessors[t].len() ); } } } } fn push_dominated_iids(&mut self, bid: BlockId, dominated_iids: &InstrIdSet) { match self.dominated_iids.entry(bid) { Entry::Vacant(e) => { e.insert(dominated_iids.clone()); } Entry::Occupied(mut e) => { e.get_mut().retain(|iid| dominated_iids.contains(iid)); } } } fn verify_func_body(&mut self) { self.verify_func_unique_iids(); // Check that the body blocks are in strict RPO order. let rpo = analysis::compute_rpo(self.func); check!( self, rpo == self.func.block_ids().collect_vec(), "Func Blocks are not in RPO order. Expected\n[{}]\nbut got\n[{}]", rpo.iter() .map(|&bid| FmtBid(self.func, bid, true).to_string()) .collect_vec() .join(", "), self.func .block_ids() .map(|bid| FmtBid(self.func, bid, true).to_string()) .collect_vec() .join(", "), ); for bid in self.func.block_ids() { self.verify_block(bid, self.func.block(bid)); } } fn verify_func_unique_iids(&self) { // InstrIds should never be used twice (although zero times is valid for // dead InstrIds). let mut seen = InstrIdSet::default(); for iid in self.func.body_iids() { check!( self, seen.insert(iid), "iid {} used twice in Func body", iid ); } } fn verify_operand( &self, src_iid: InstrId, op_vid: ValueId, op_idx: usize, dominated_iids: &InstrIdSet, ) { match op_vid.full() { FullInstrId::Constant(cid) => { check!( self, self.func.constants.get(cid).is_some(), "iid {} refers to missing constant {}", src_iid, cid ) } FullInstrId::Instr(op_iid) => { let op_instr = self.func.get_instr(op_iid); // Technically this is a subset of the following domination // check - but gives a better error message. check!( self, op_instr.is_some(), "iid {} refers to missing instr {}", src_iid, op_iid ); check!( self, dominated_iids.contains(&op_iid), "iid {} doesn't dominate use at {}", FmtVid(self.func, op_vid, true, self.strings), FmtVid(self.func, ValueId::from_instr(src_iid), true, self.strings), ); match op_instr.unwrap() { Instr::Special(Special::Tombstone) => { // We should never see a tombstone as part of the graph. check_failed!( self, "iid {} operand {} ({})is a tombstone", src_iid, op_idx, FmtVid(self.func, op_vid, true, self.strings) ); } _ => {} } } FullInstrId::None => { check_failed!(self, "iid {} operand {} is none", src_iid, op_idx); } } } fn verify_block_args(&self, iid: InstrId, bid: BlockId, args: usize) { // Make sure that the target block is expecting the args. let expected_args = self.func.block(bid).params.len(); check!( self, expected_args == args, "iid {iid} is a jump with {args} args to block {bid} expecting {expected_args} args", ); } fn verify_selects(&self, n: usize, block: &Block, iid: InstrId, iid_idx: usize) { for i in 1..=n { let select_iid = if let Some(iid) = block.iids.get(iid_idx + i) { *iid } else { check_failed!( self, "iid {} returns {} values but block doesn't contain enough iids (only followed by {})", iid, n, i - 1 ) }; check!( self, matches!( self.func.instr(select_iid), Instr::Special(Special::Select(..)) ), "iid {} returns {} values but is only followed by {} selects", iid, n, i - 1 ); } } fn verify_select( &self, iid: InstrId, iid_idx: usize, prev_vid: Option<ValueId>, target_vid: ValueId, idx: u32, ) { // The select instruction must follow either another select for the // same target or the target it's selecting from. check!( self, iid_idx > 0, "iid {} select cannot be first instr in block", iid ); let prev_vid = prev_vid.unwrap(); let prev_instr = self.func.instr(prev_vid.expect_instr("instr expected")); if prev_vid != target_vid { // If the previous vid is not our target then it must be a // select with the same target as us. match *prev_instr { Instr::Special(Special::Select(prev_target, prev_idx)) => { if prev_target != target_vid { check_failed!( self, "iid {} select with target {} follows a select with a different target instr {}", iid, FmtRawVid(target_vid), FmtRawVid(prev_target) ); } if prev_idx + 1 != idx { check_failed!( self, "iid {} select with index {} follows a non-contiguous select index {}", iid, idx, prev_idx ); } } _ => { check_failed!(self, "iid {} select is not contiguous with its target", iid); } } } else { // Check that the previous instruction expects a select. The actual // number of expected selects was checked when we saw the previous // instruction. let expects_select = match *prev_instr { Instr::Call(ref call) => call.num_rets >= 2, Instr::Hhbc(Hhbc::ClassGetTS(..)) => true, Instr::MemberOp(ref op) => op.num_values() >= 2, _ => false, }; if !expects_select { check_failed!( self, "iid {} select follows non-selectable instr {:?}", iid, prev_instr ); } } } fn verify_instr( &self, block: &Block, iid: InstrId, iid_idx: usize, instr: &Instr, dominated_iids: &mut InstrIdSet, ) { // Ensure that all operands exist. for (op_idx, op_vid) in instr.operands().iter().copied().enumerate() { self.verify_operand(iid, op_vid, op_idx, dominated_iids); } dominated_iids.insert(iid); // Ensure all edges are valid. for &bid in instr.edges() { check!( self, self.func.blocks.get(bid).is_some(), "iid {} refers to missing block {}", iid, bid ); } let prev_vid = if iid_idx > 0 { block .iids .get(iid_idx - 1) .copied() .map(ValueId::from_instr) } else { None }; // Special cases for individual instructions. match *instr { Instr::Call(ref call) => { if call.num_rets > 1 { self.verify_selects(call.num_rets as usize, block, iid, iid_idx); } } Instr::Hhbc(Hhbc::ClassGetTS(..)) => { self.verify_selects(2, block, iid, iid_idx); } Instr::MemberOp(ref op) => { let num_rets = op.num_values(); if num_rets > 1 { self.verify_selects(num_rets, block, iid, iid_idx); } } Instr::Terminator(Terminator::CallAsync(_, targets)) => { self.verify_block_args(iid, targets[0], 1); self.verify_block_args(iid, targets[1], 1); } Instr::Terminator(Terminator::Enter(bid, _) | Terminator::Jmp(bid, _)) => { self.verify_block_args(iid, bid, 0); } Instr::Terminator(Terminator::JmpArgs(bid, ref vids, _)) => { check!( self, !vids.is_empty(), "iid {} is JmpArgs with no args!", iid ); self.verify_block_args(iid, bid, vids.len()); } Instr::Terminator(Terminator::JmpOp { targets, .. }) => { self.verify_block_args(iid, targets[0], 0); self.verify_block_args(iid, targets[1], 0); } Instr::Terminator( Terminator::IterInit(ref args, _) | Terminator::IterNext(ref args), ) => { self.verify_block_args(iid, args.targets[0], 0); self.verify_block_args(iid, args.targets[1], 0); } Instr::Special(Special::Param) => { check_failed!(self, "Param iid {} shouldn't be in block instrs", iid); } Instr::Special(Special::IrToBc(IrToBc::PushConstant(vid))) => { check!( self, vid.is_constant(), "vid {} PushConstant must refer to a ConstantId", iid ); } Instr::Special(Special::Select(target_vid, idx)) => { self.verify_select(iid, iid_idx, prev_vid, target_vid, idx); } Instr::Special(Special::Tombstone) => { // We should never see a tombstone as part of the graph. check_failed!(self, "iid {} is a tombstone", iid); } _ => {} } } } pub fn verify_func(func: &Func<'_>, flags: &Flags, strings: &StringInterner) { let mut verify = VerifyFunc::new(func, flags, strings); verify.verify_func_body(); }
TOML
hhvm/hphp/hack/src/hackc/print_expr/Cargo.toml
# @generated by autocargo [package] name = "print_expr" version = "0.0.0" edition = "2021" [lib] path = "lib.rs" [dependencies] anyhow = "1.0.71" bstr = { version = "1.4.0", features = ["serde", "std", "unicode"] } bumpalo = { version = "3.11.1", features = ["collections"] } core_utils_rust = { version = "0.0.0", path = "../../utils/core" } emit_type_hint = { version = "0.0.0", path = "../emitter/cargo/emit_type_hint" } error = { version = "0.0.0", path = "../error/cargo/error" } escaper = { version = "0.0.0", path = "../../utils/escaper" } hhbc = { version = "0.0.0", path = "../hhbc/cargo/hhbc" } hhbc_string_utils = { version = "0.0.0", path = "../utils/cargo/hhbc_string_utils" } lazy_static = "1.4" naming_special_names_rust = { version = "0.0.0", path = "../../naming" } oxidized = { version = "0.0.0", path = "../../oxidized" } regex = "1.9.2" thiserror = "1.0.43" write_bytes = { version = "0.0.0", path = "../../utils/write_bytes/write_bytes" }
Rust
hhvm/hphp/hack/src/hackc/print_expr/context.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use crate::special_class_resolver::SpecialClassResolver; #[derive(Clone)] pub struct Context<'a> { pub(crate) special_class_resolver: &'a dyn SpecialClassResolver, pub(crate) dump_lambdas: bool, } impl<'a> Context<'a> { pub fn new(special_class_resolver: &'a dyn SpecialClassResolver) -> Self { Self { special_class_resolver, dump_lambdas: false, } } }
Rust
hhvm/hphp/hack/src/hackc/print_expr/lib.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. mod context; mod print; mod special_class_resolver; mod write; pub use context::Context; pub use print::expr_to_string_lossy; pub use print::external_print_expr as print_expr; pub use print::ExprEnv; pub use print::HhasBodyEnv; pub use special_class_resolver::SpecialClassResolver; pub use write::Error;
Rust
hhvm/hphp/hack/src/hackc/print_expr/print.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::borrow::Cow; use std::io::Result; use std::io::Write; use std::write; use bstr::BString; use bstr::ByteSlice; use core_utils_rust::add_ns; use error::ErrorKind; use hhbc::ClassName; use hhbc_string_utils::integer; use hhbc_string_utils::is_class; use hhbc_string_utils::is_parent; use hhbc_string_utils::is_self; use hhbc_string_utils::is_static; use hhbc_string_utils::is_xhp; use hhbc_string_utils::lstrip; use hhbc_string_utils::lstrip_bslice; use hhbc_string_utils::mangle; use hhbc_string_utils::strip_global_ns; use hhbc_string_utils::strip_ns; use hhbc_string_utils::types; use lazy_static::__Deref; use lazy_static::lazy_static; use naming_special_names_rust::classes; use oxidized::ast; use oxidized::ast_defs; use oxidized::ast_defs::ParamKind; use oxidized::local_id; use regex::Regex; use write_bytes::write_bytes; use crate::context::Context; use crate::write; use crate::write::Error; #[derive(Default, Debug, Clone, Eq, PartialEq)] #[repr(C)] pub struct HhasBodyEnv<'a> { pub is_namespaced: bool, pub class_info: Option<(hhbc::ClassishKind, &'a str)>, pub parent_name: Option<&'a str>, } pub struct ExprEnv<'arena, 'e> { pub codegen_env: Option<&'e HhasBodyEnv<'arena>>, } fn print_key_value( ctx: &Context<'_>, w: &mut dyn Write, env: &ExprEnv<'_, '_>, k: &ast::Expr, v: &ast::Expr, ) -> Result<()> { print_key_value_(ctx, w, env, k, print_expr, v) } fn print_key_value_<K, KeyPrinter>( ctx: &Context<'_>, w: &mut dyn Write, env: &ExprEnv<'_, '_>, k: K, mut kp: KeyPrinter, v: &ast::Expr, ) -> Result<()> where KeyPrinter: FnMut(&Context<'_>, &mut dyn Write, &ExprEnv<'_, '_>, K) -> Result<()>, { kp(ctx, w, env, k)?; w.write_all(b" => ")?; print_expr(ctx, w, env, v) } fn print_field( ctx: &Context<'_>, w: &mut dyn Write, env: &ExprEnv<'_, '_>, field: &ast::Field, ) -> Result<()> { print_key_value(ctx, w, env, &field.0, &field.1) } fn print_afield( ctx: &Context<'_>, w: &mut dyn Write, env: &ExprEnv<'_, '_>, afield: &ast::Afield, ) -> Result<()> { use ast::Afield as A; match afield { A::AFvalue(e) => print_expr(ctx, w, env, e), A::AFkvalue(k, v) => print_key_value(ctx, w, env, k, v), } } fn print_afields( ctx: &Context<'_>, w: &mut dyn Write, env: &ExprEnv<'_, '_>, afields: impl AsRef<[ast::Afield]>, ) -> Result<()> { write::concat_by(w, ", ", afields, |w, i| print_afield(ctx, w, env, i)) } fn print_uop(w: &mut dyn Write, op: ast::Uop) -> Result<()> { use ast::Uop as U; w.write_all(match op { U::Utild => b"~", U::Unot => b"!", U::Uplus => b"+", U::Uminus => b"-", U::Uincr => b"++", U::Udecr => b"--", U::Usilence => b"@", U::Upincr | U::Updecr => { return Err(Error::fail("string_of_uop - should have been captures earlier").into()); } }) } fn print_key_values_<K, KeyPrinter>( ctx: &Context<'_>, w: &mut dyn Write, env: &ExprEnv<'_, '_>, mut kp: KeyPrinter, kvs: impl AsRef<[(K, ast::Expr)]>, ) -> Result<()> where KeyPrinter: Fn(&Context<'_>, &mut dyn Write, &ExprEnv<'_, '_>, &K) -> Result<()>, { write::concat_by(w, ", ", kvs, |w, (k, v)| { print_key_value_(ctx, w, env, k, &mut kp, v) }) } fn print_expr_darray<K, KeyPrinter>( ctx: &Context<'_>, w: &mut dyn Write, env: &ExprEnv<'_, '_>, kp: KeyPrinter, kvs: impl AsRef<[(K, ast::Expr)]>, ) -> Result<()> where KeyPrinter: Fn(&Context<'_>, &mut dyn Write, &ExprEnv<'_, '_>, &K) -> Result<()>, { write::wrap_by_(w, "darray[", "]", |w| { print_key_values_(ctx, w, env, kp, kvs) }) } fn print_expr_varray( ctx: &Context<'_>, w: &mut dyn Write, env: &ExprEnv<'_, '_>, varray: &[ast::Expr], ) -> Result<()> { write::wrap_by_(w, "varray[", "]", |w| { write::concat_by(w, ", ", varray, |w, e| print_expr(ctx, w, env, e)) }) } fn print_shape_field_name( _: &Context<'_>, w: &mut dyn Write, _: &ExprEnv<'_, '_>, field: &ast::ShapeFieldName, ) -> Result<()> { use ast::ShapeFieldName as S; match field { S::SFlitInt((_, s)) => print_expr_int(w, s.as_ref()), S::SFlitStr((_, s)) => print_expr_string(w, s), S::SFclassConst(_, (_, s)) => print_expr_string(w, s.as_bytes()), } } fn print_expr_int(w: &mut dyn Write, i: &str) -> Result<()> { match integer::to_decimal(i) { Ok(s) => w.write_all(s.as_bytes()), Err(_) => Err(Error::fail("ParseIntError").into()), } } fn print_expr_string(w: &mut dyn Write, s: &[u8]) -> Result<()> { fn escape_char(c: u8) -> Option<Cow<'static, [u8]>> { match c { b'\n' => Some(Cow::Borrowed(b"\\n")), b'\r' => Some(Cow::Borrowed(b"\\r")), b'\t' => Some(Cow::Borrowed(b"\\t")), b'\\' => Some(Cow::Borrowed(b"\\\\")), b'"' => Some(Cow::Borrowed(b"\\\"")), b'$' => Some(Cow::Borrowed(b"\\$")), c if escaper::is_lit_printable(c) => None, c => { let mut buf = vec![]; write!(buf, "\\{:03o}", c).unwrap(); Some(buf.into()) } } } write::wrap_by(w, "\"", |w| { w.write_all(&escaper::escape_bstr_by(s.as_bstr().into(), escape_char)) }) } fn print_expr_to_string( ctx: &Context<'_>, env: &ExprEnv<'_, '_>, expr: &ast::Expr, ) -> Result<BString> { let mut buf = Vec::new(); print_expr(ctx, &mut buf, env, expr).map_err(|e| match write::into_error(e) { Error::NotImpl(m) => Error::NotImpl(m), e => Error::Fail(format!("Failed: {}", e)), })?; Ok(buf.into()) } fn print_expr( ctx: &Context<'_>, w: &mut dyn Write, env: &ExprEnv<'_, '_>, ast::Expr(_, _, expr): &ast::Expr, ) -> Result<()> { fn adjust_id<'a>(env: &ExprEnv<'_, '_>, id: &'a str) -> Cow<'a, str> { match env.codegen_env { Some(env) => { if env.is_namespaced && id .as_bytes() .iter() .rposition(|c| *c == b'\\') .map_or(true, |i| i < 1) { strip_global_ns(id).into() } else { add_ns(id) } } _ => id.into(), } } fn print_expr_id<'a>(w: &mut dyn Write, env: &ExprEnv<'_, '_>, s: &'a str) -> Result<()> { w.write_all(adjust_id(env, s).as_bytes()) } fn fmt_class_name<'a>(is_class_constant: bool, id: Cow<'a, str>) -> Cow<'a, str> { let stripped = strip_global_ns(&id); let mangled = if is_xhp(&id) { mangle(stripped.to_string()) } else { stripped.to_string() }; if is_class_constant { format!("\\{}", mangled).into() } else { mangled.into() } } fn get_class_name_from_id<'e>( ctx: &Context<'_>, env: Option<&'e HhasBodyEnv<'_>>, should_format: bool, is_class_constant: bool, id: &'e str, ) -> Cow<'e, str> { if id == classes::SELF || id == classes::PARENT || id == classes::STATIC { let name = ctx.special_class_resolver.resolve(env, id); return fmt_class_name(is_class_constant, name); } fn get<'a>(should_format: bool, is_class_constant: bool, id: &'a str) -> Cow<'a, str> { if should_format { fmt_class_name(is_class_constant, id.into()) } else { id.into() } } if env.is_some() { let alloc = bumpalo::Bump::new(); let class_id = ClassName::from_ast_name_and_mangle(&alloc, id); let id = class_id.unsafe_as_str(); get(should_format, is_class_constant, id) .into_owned() .into() } else { get(should_format, is_class_constant, id) } } fn handle_possible_colon_colon_class_expr( ctx: &Context<'_>, w: &mut dyn Write, env: &ExprEnv<'_, '_>, is_array_get: bool, e_: &ast::Expr_, ) -> Result<Option<()>> { match e_.as_class_const() { Some(( ast::ClassId(_, _, ast::ClassId_::CIexpr(ast::Expr(_, _, ast::Expr_::Id(id)))), (_, s2), )) if is_class(s2) && !(is_self(&id.1) || is_parent(&id.1) || is_static(&id.1)) => { Ok(Some({ let s1 = get_class_name_from_id(ctx, env.codegen_env, false, false, &id.1); if is_array_get { print_expr_id(w, env, s1.as_ref())? } else { print_expr_string(w, s1.as_bytes())? } })) } _ => Ok(None), } } use ast::Expr_; match expr { Expr_::Id(id) => print_expr_id(w, env, id.1.as_ref()), Expr_::Lvar(lid) => w.write_all((lid.1).1.as_bytes()), Expr_::Float(f) => { if f.contains('E') || f.contains('e') { let s = format!( "{:.1E}", f.parse::<f64>() .map_err(|_| Error::fail(format!("ParseFloatError: {}", f)))? ) // to_uppercase() here because s might be "inf" or "nan" .to_uppercase(); lazy_static! { static ref UNSIGNED_EXP: Regex = Regex::new(r"(?P<first>E)(?P<second>\d+)").unwrap(); static ref SIGNED_SINGLE_DIGIT_EXP: Regex = Regex::new(r"(?P<first>E[+-])(?P<second>\d$)").unwrap(); } // turn mEn into mE+n let s = UNSIGNED_EXP.replace(&s, "${first}+${second}"); // turn mE+n or mE-n into mE+0n or mE-0n (where n is a single digit) let s = SIGNED_SINGLE_DIGIT_EXP.replace(&s, "${first}0${second}"); w.write_all(s.as_bytes()) } else { w.write_all(f.as_bytes()) } } Expr_::Int(i) => print_expr_int(w, i.as_ref()), Expr_::String(s) => print_expr_string(w, s), Expr_::Null => w.write_all(b"NULL"), Expr_::True => w.write_all(b"true"), Expr_::False => w.write_all(b"false"), Expr_::ValCollection(vc) if matches!(vc.0.1, ast::VcKind::Vec) => { write::wrap_by_(w, "vec[", "]", |w| { write::concat_by(w, ", ", &vc.2, |w, e| print_expr(ctx, w, env, e)) }) } Expr_::ValCollection(vc) if matches!(vc.0.1, ast::VcKind::Keyset) => { write::wrap_by_(w, "keyset[", "]", |w| { write::concat_by(w, ", ", &vc.2, |w, e| print_expr(ctx, w, env, e)) }) } Expr_::KeyValCollection(kvc) if matches!(kvc.0.1, ast::KvcKind::Dict) => { write::wrap_by_(w, "dict[", "]", |w| { write::concat_by(w, ", ", &kvc.2, |w, f| print_field(ctx, w, env, f)) }) } Expr_::Collection(c) => { let name = strip_ns((c.0).1.as_str()); let name = types::fix_casing(name); match name { "Set" | "Pair" | "Vector" | "Map" | "ImmSet" | "ImmVector" | "ImmMap" => { w.write_all(b"HH\\")?; w.write_all(name.as_bytes())?; write::wrap_by_(w, " {", "}", |w| { Ok(if !c.2.is_empty() { w.write_all(b" ")?; print_afields(ctx, w, env, &c.2)?; w.write_all(b" ")?; }) }) } _ => Err( Error::fail(format!("Default value for an unknow collection - {}", name)) .into(), ), } } Expr_::Shape(fl) => print_expr_darray(ctx, w, env, print_shape_field_name, fl), Expr_::Binop(x) => { let ast::Binop { bop, lhs, rhs } = &**x; print_expr(ctx, w, env, lhs)?; w.write_all(b" ")?; print_bop(w, bop)?; w.write_all(b" ")?; print_expr(ctx, w, env, rhs) } Expr_::Call(c) => { let ast::CallExpr { func, args, unpacked_arg, .. } = &**c; match func.as_id() { Some(ast_defs::Id(_, call_id)) => { w.write_all(lstrip(adjust_id(env, call_id).as_ref(), "\\").as_bytes())? } None => { let buf = print_expr_to_string(ctx, env, func)?; w.write_all(lstrip_bslice(&buf, br"\"))? } }; write::paren(w, |w| { write::concat_by(w, ", ", args, |w, (pk, e)| match pk { ParamKind::Pnormal => print_expr(ctx, w, env, e), ParamKind::Pinout(_) => Err(Error::fail("illegal default value").into()), })?; match unpacked_arg { None => Ok(()), Some(e) => { if !args.is_empty() { w.write_all(b", ")?; } // TODO: Should probably have ... also print_expr(ctx, w, env, e) } } }) } Expr_::New(x) => { let (cid, _, es, unpacked_element, _) = &**x; match cid.2.as_ciexpr() { Some(ci_expr) => { w.write_all(b"new ")?; match ci_expr.2.as_id() { Some(ast_defs::Id(_, cname)) => w.write_all( lstrip( &adjust_id( env, ClassName::from_ast_name_and_mangle( &bumpalo::Bump::new(), cname, ) .unsafe_as_str(), ), "\\", ) .as_bytes(), )?, None => { let buf = print_expr_to_string(ctx, env, ci_expr)?; w.write_all(lstrip_bslice(&buf, br"\"))? } } write::paren(w, |w| { write::concat_by(w, ", ", es, |w, e| print_expr(ctx, w, env, e))?; match unpacked_element { None => Ok(()), Some(e) => { w.write_all(b", ")?; print_expr(ctx, w, env, e) } } }) } None => { match cid.2.as_ci() { Some(id) => { // Xml exprs rewritten as New exprs come // through here. print_xml(ctx, w, env, &id.1, es) } None => Err(Error::NotImpl(format!("{}:{}", file!(), line!())).into()), } } } } Expr_::ClassGet(cg) => { match &(cg.0).2 { ast::ClassId_::CIexpr(e) => match e.as_id() { Some(id) => w.write_all( get_class_name_from_id( ctx, env.codegen_env, true, /* should_format */ false, /* is_class_constant */ &id.1, ) .as_bytes(), )?, _ => print_expr(ctx, w, env, e)?, }, _ => return Err(Error::fail("TODO Unimplemented unexpected non-CIexpr").into()), } w.write_all(b"::")?; match &cg.1 { ast::ClassGetExpr::CGstring((_, litstr)) => w.write_all(litstr.as_bytes()), ast::ClassGetExpr::CGexpr(e) => print_expr(ctx, w, env, e), } } Expr_::ClassConst(cc) => { if let Some(e1) = (cc.0).2.as_ciexpr() { handle_possible_colon_colon_class_expr(ctx, w, env, false, expr)?.map_or_else( || { let s2 = &(cc.1).1; match e1.2.as_id() { Some(ast_defs::Id(_, s1)) => { let s1 = get_class_name_from_id(ctx, env.codegen_env, true, true, s1); write::concat_str_by(w, "::", [&s1.into(), s2]) } _ => { print_expr(ctx, w, env, e1)?; w.write_all(b"::")?; w.write_all(s2.as_bytes()) } } }, Ok, ) } else { Err(Error::fail("TODO: Only expected CIexpr in class_const").into()) } } Expr_::Unop(u) => match u.0 { ast::Uop::Upincr => { print_expr(ctx, w, env, &u.1)?; w.write_all(b"++") } ast::Uop::Updecr => { print_expr(ctx, w, env, &u.1)?; w.write_all(b"--") } _ => { print_uop(w, u.0)?; print_expr(ctx, w, env, &u.1) } }, Expr_::ObjGet(og) => { print_expr(ctx, w, env, &og.0)?; w.write_all(match og.2 { ast::OgNullFlavor::OGNullthrows => b"->", ast::OgNullFlavor::OGNullsafe => b"?->", })?; print_expr(ctx, w, env, &og.1) } Expr_::Clone(e) => { w.write_all(b"clone ")?; print_expr(ctx, w, env, e) } Expr_::ArrayGet(ag) => { print_expr(ctx, w, env, &ag.0)?; write::square(w, |w| { write::option(w, &ag.1, |w, e: &ast::Expr| { handle_possible_colon_colon_class_expr(ctx, w, env, true, &e.2) .transpose() .unwrap_or_else(|| print_expr(ctx, w, env, e)) }) }) } Expr_::String2(ss) => write::concat_by(w, " . ", ss, |w, s| print_expr(ctx, w, env, s)), Expr_::PrefixedString(s) => { w.write_all(s.0.as_bytes())?; w.write_all(b" . ")?; print_expr(ctx, w, env, &s.1) } Expr_::Eif(eif) => { print_expr(ctx, w, env, &eif.0)?; w.write_all(b" ? ")?; write::option(w, &eif.1, |w, etrue| print_expr(ctx, w, env, etrue))?; w.write_all(b" : ")?; print_expr(ctx, w, env, &eif.2) } Expr_::Cast(c) => { write::paren(w, |w| print_hint(w, false, &c.0))?; print_expr(ctx, w, env, &c.1) } Expr_::Pipe(p) => { print_expr(ctx, w, env, &p.1)?; w.write_all(b" |> ")?; print_expr(ctx, w, env, &p.2) } Expr_::Is(i) => { print_expr(ctx, w, env, &i.0)?; w.write_all(b" is ")?; print_hint(w, true, &i.1) } Expr_::As(a) => { print_expr(ctx, w, env, &a.0)?; w.write_all(if a.2 { b" ?as " } else { b" as " })?; print_hint(w, true, &a.1) } Expr_::Varray(va) => print_expr_varray(ctx, w, env, &va.1), Expr_::Darray(da) => print_expr_darray(ctx, w, env, print_expr, &da.1), Expr_::Tuple(t) => write::wrap_by_(w, "varray[", "]", |w| { // A tuple is represented by a varray when using reflection. write::concat_by(w, ", ", t, |w, i| print_expr(ctx, w, env, i)) }), Expr_::List(l) => write::wrap_by_(w, "list(", ")", |w| { write::concat_by(w, ", ", l, |w, i| print_expr(ctx, w, env, i)) }), Expr_::Yield(y) => { w.write_all(b"yield ")?; print_afield(ctx, w, env, y) } Expr_::Await(e) => { w.write_all(b"await ")?; print_expr(ctx, w, env, e) } Expr_::Import(i) => { print_import_flavor(w, &i.0)?; w.write_all(b" ")?; print_expr(ctx, w, env, &i.1) } Expr_::Xml(_) => { Err(Error::fail("expected Xml to be converted to New during rewriting").into()) } Expr_::Efun(f) => print_efun(ctx, w, env, f), Expr_::FunctionPointer(fp) => { let (fp_id, targs) = &**fp; match fp_id { ast::FunctionPtrId::FPId(ast::Id(_, sid)) => { w.write_all(lstrip(adjust_id(env, sid).as_ref(), "\\").as_bytes())? } ast::FunctionPtrId::FPClassConst(ast::ClassId(_, _, class_id), (_, meth_name)) => { match class_id { ast::ClassId_::CIexpr(e) => match e.as_id() { Some(id) => w.write_all( get_class_name_from_id( ctx, env.codegen_env, true, /* should_format */ false, /* is_class_constant */ &id.1, ) .as_bytes(), )?, _ => print_expr(ctx, w, env, e)?, }, _ => { return Err(Error::fail( "TODO Unimplemented unexpected non-CIexpr in function pointer", ) .into()); } } w.write_all(b"::")?; w.write_all(meth_name.as_bytes())? } }; write::wrap_by_(w, "<", ">", |w| { write::concat_by(w, ", ", targs, |w, _targ| w.write_all(b"_")) }) } Expr_::Omitted => Ok(()), Expr_::Lfun(lfun) => { if ctx.dump_lambdas { let fun_ = &lfun.0; write::paren(w, |w| { write::paren(w, |w| { write::concat_by(w, ", ", &fun_.params, |w, param| { print_fparam(ctx, w, env, param) }) })?; w.write_all(b" ==> ")?; print_block_(ctx, w, env, &fun_.body.fb_ast) }) } else { Err(Error::fail( "expected Lfun to be converted to Efun during closure conversion print_expr", ) .into()) } } Expr_::ETSplice(splice) => { w.write_all(b"${")?; print_expr(ctx, w, env, splice)?; w.write_all(b"}") } Expr_::EnumClassLabel(ecl) => match &ecl.0 { Some(ast_defs::Id(_, s1)) => { let s1 = get_class_name_from_id(ctx, env.codegen_env, true, true, s1); write::concat_str_by(w, "#", [&s1.into(), &ecl.1]) } None => { w.write_all(b"#")?; w.write_all(ecl.1.as_bytes()) } }, Expr_::ReadonlyExpr(expr) => { w.write_all(b"readonly(")?; print_expr(ctx, w, env, expr)?; w.write_all(b")") } Expr_::Invalid(expr_opt) => match &expr_opt.deref() { Some(expr) => print_expr(ctx, w, env, expr), _ => Ok(()), }, Expr_::Package(_) | Expr_::Dollardollar(_) | Expr_::ExpressionTree(_) | Expr_::Hole(_) | Expr_::KeyValCollection(_) | Expr_::Lplaceholder(_) | Expr_::MethodCaller(_) | Expr_::Pair(_) | Expr_::This | Expr_::Upcast(_) | Expr_::ValCollection(_) => { todo!("T117477443: Unimplemented: Cannot print: {:?}", expr) } } } fn print_xml( ctx: &Context<'_>, w: &mut dyn Write, env: &ExprEnv<'_, '_>, id: &str, es: &[ast::Expr], ) -> Result<()> { use ast::Expr; use ast::Expr_; fn syntax_error() -> Error { Error::NotImpl(String::from("print_xml: unexpected syntax")) } fn print_xhp_attr( ctx: &Context<'_>, w: &mut dyn Write, env: &ExprEnv<'_, '_>, attr: &(ast_defs::ShapeFieldName, ast::Expr), ) -> Result<()> { match attr { (ast_defs::ShapeFieldName::SFlitStr(s), e) => print_key_value_( ctx, w, env, &s.1, |_, w, _, k| print_expr_string(w, k.as_slice()), e, ), _ => Err(syntax_error().into()), } } let (attrs, children) = if es.len() < 2 { return Err(syntax_error().into()); } else { match (&es[0], &es[1]) { (Expr(_, _, Expr_::Shape(attrs)), Expr(_, _, Expr_::Varray(children))) => { (attrs, &children.1) } _ => return Err(syntax_error().into()), } }; let env = ExprEnv { codegen_env: env.codegen_env, }; write!(w, "new {}", mangle(id.into()))?; write::paren(w, |w| { write::wrap_by_(w, "darray[", "]", |w| { write::concat_by(w, ", ", attrs, |w, attr| print_xhp_attr(ctx, w, &env, attr)) })?; w.write_all(b", ")?; print_expr_varray(ctx, w, &env, children)?; w.write_all(b", __FILE__, __LINE__") }) } fn print_efun( ctx: &Context<'_>, w: &mut dyn Write, env: &ExprEnv<'_, '_>, efun: &ast::Efun, ) -> Result<()> { let f = &efun.fun; if f.fun_kind.is_fasync() || f.fun_kind.is_fasync_generator() { write!(w, "async ",)?; } w.write_all(b"function ")?; write::paren(w, |w| { write::concat_by(w, ", ", &f.params, |w, p| print_fparam(ctx, w, env, p)) })?; w.write_all(b" ")?; let use_list = &efun.use_; if !use_list.is_empty() { w.write_all(b"use ")?; write::paren(w, |w| { write::concat_by( w, ", ", use_list, |w: &mut dyn Write, ast::CaptureLid(_, ast::Lid(_, id))| { w.write_all(local_id::get_name(id).as_bytes()) }, ) })?; w.write_all(b" ")?; } print_block_(ctx, w, env, &f.body.fb_ast) } fn print_block( ctx: &Context<'_>, w: &mut dyn Write, env: &ExprEnv<'_, '_>, block: &[ast::Stmt], ) -> Result<()> { match block { [] | [ast::Stmt(_, ast::Stmt_::Noop)] => Ok(()), [ast::Stmt(_, ast::Stmt_::Block(b))] if b.len() == 1 => print_block_(ctx, w, env, b), [_, _, ..] => print_block_(ctx, w, env, block), [stmt] => print_statement(ctx, w, env, stmt), } } fn print_block_( ctx: &Context<'_>, w: &mut dyn Write, env: &ExprEnv<'_, '_>, block: &[ast::Stmt], ) -> Result<()> { write::wrap_by_(w, "{\n", "}\n", |w| { write::concat(w, block, |w, stmt| { if !matches!(stmt.1, ast::Stmt_::Noop) { w.write_all(b" ")?; print_statement(ctx, w, env, stmt)?; } Ok(()) }) }) } fn print_statement( ctx: &Context<'_>, w: &mut dyn Write, env: &ExprEnv<'_, '_>, stmt: &ast::Stmt, ) -> Result<()> { use ast::Stmt_ as S_; match &stmt.1 { S_::Return(expr) => write::wrap_by_(w, "return", ";\n", |w| { write::option(w, &**expr, |w, e| { w.write_all(b" ")?; print_expr(ctx, w, env, e) }) }), S_::Expr(expr) => { print_expr(ctx, w, env, expr)?; w.write_all(b";\n") } S_::Throw(expr) => write::wrap_by_(w, "throw ", ";\n", |w| print_expr(ctx, w, env, expr)), S_::Break => w.write_all(b"break;\n"), S_::Continue => w.write_all(b"continue;\n"), S_::While(x) => { let (cond, block) = &**x; write::wrap_by_(w, "while (", ") ", |w| print_expr(ctx, w, env, cond))?; print_block(ctx, w, env, block.as_ref()) } S_::If(x) => { let (cond, if_block, else_block) = &**x; write::wrap_by_(w, "if (", ") ", |w| print_expr(ctx, w, env, cond))?; print_block(ctx, w, env, if_block)?; let mut buf = Vec::new(); print_block(ctx, &mut buf, env, else_block).map_err(|e| { match write::into_error(e) { e @ Error::NotImpl(_) => e, e => Error::Fail(format!("Failed: {}", e)), } })?; if !buf.is_empty() { write_bytes!(w, " else {}", BString::from(buf))?; }; Ok(()) } S_::Block(block) => print_block_(ctx, w, env, block), S_::Noop => Ok(()), /* TODO(T29869930) */ _ => w.write_all(b"TODO Unimplemented NYI: Default value printing"), } } fn print_fparam( ctx: &Context<'_>, w: &mut dyn Write, env: &ExprEnv<'_, '_>, param: &ast::FunParam, ) -> Result<()> { if param.callconv.is_pinout() { w.write_all(b"inout ")?; } if param.is_variadic { w.write_all(b"...")?; } write::option(w, &(param.type_hint).1, |w, h| { print_hint(w, true, h)?; w.write_all(b" ") })?; w.write_all(param.name.as_bytes())?; write::option(w, &param.expr, |w, e| { w.write_all(b" = ")?; print_expr(ctx, w, env, e) }) } fn print_bop(w: &mut dyn Write, bop: &ast_defs::Bop) -> Result<()> { use ast_defs::Bop; match bop { Bop::Plus => w.write_all(b"+"), Bop::Minus => w.write_all(b"-"), Bop::Star => w.write_all(b"*"), Bop::Slash => w.write_all(b"/"), Bop::Eqeq => w.write_all(b"=="), Bop::Eqeqeq => w.write_all(b"==="), Bop::Starstar => w.write_all(b"**"), Bop::Eq(None) => w.write_all(b"="), Bop::Eq(Some(bop)) => { w.write_all(b"=")?; print_bop(w, bop) } Bop::Ampamp => w.write_all(b"&&"), Bop::Barbar => w.write_all(b"||"), Bop::Lt => w.write_all(b"<"), Bop::Lte => w.write_all(b"<="), Bop::Cmp => w.write_all(b"<=>"), Bop::Gt => w.write_all(b">"), Bop::Gte => w.write_all(b">="), Bop::Dot => w.write_all(b"."), Bop::Amp => w.write_all(b"&"), Bop::Bar => w.write_all(b"|"), Bop::Ltlt => w.write_all(b"<<"), Bop::Gtgt => w.write_all(b">>"), Bop::Percent => w.write_all(b"%"), Bop::Xor => w.write_all(b"^"), Bop::Diff => w.write_all(b"!="), Bop::Diff2 => w.write_all(b"!=="), Bop::QuestionQuestion => w.write_all(b"??"), } } fn print_hint(w: &mut dyn Write, ns: bool, hint: &ast::Hint) -> Result<()> { let alloc = bumpalo::Bump::new(); let h = emit_type_hint::fmt_hint(&alloc, &[], false, hint).map_err(|e| match e.kind() { ErrorKind::Unrecoverable(s) => Error::fail(s), _ => Error::fail("Error printing hint"), })?; let stripped = if ns { &h } else { strip_ns(&h) }; w.write_all(stripped.as_bytes()) } fn print_import_flavor(w: &mut dyn Write, flavor: &ast::ImportFlavor) -> Result<()> { use ast::ImportFlavor as F; w.write_all(match flavor { F::Include => b"include", F::Require => b"require", F::IncludeOnce => b"include_once", F::RequireOnce => b"require_once", }) } /// Convert an `Expr` to a `String` of the equivalent source code. /// /// This is a debugging tool abusing a printer written for bytecode /// emission. It does not support all Hack expressions, and panics /// on unsupported syntax. /// /// If you have an `Expr` with positions, you are much better off /// getting the source code at those positions rather than using this. pub fn expr_to_string_lossy(mut ctx: Context<'_>, expr: &ast::Expr) -> String { ctx.dump_lambdas = true; let env = ExprEnv { codegen_env: None }; let mut escaped_src = Vec::new(); print_expr(&ctx, &mut escaped_src, &env, expr).expect("Printing failed"); let bs = escaper::unescape_double(unsafe { std::str::from_utf8_unchecked(&escaped_src) }) .expect("Unescaping failed"); let s = String::from_utf8_lossy(&bs); s.to_string() } pub fn external_print_expr( ctx: &Context<'_>, w: &mut dyn std::io::Write, env: &ExprEnv<'_, '_>, expr: &ast::Expr, ) -> std::result::Result<(), Error> { print_expr(ctx, w, env, expr).map_err(write::into_error)?; w.flush().map_err(write::into_error)?; Ok(()) }