1 //! Parser for .clif files. 2 3 use crate::error::{Location, ParseError, ParseResult}; 4 use crate::heap_command::{HeapCommand, HeapType}; 5 use crate::isaspec; 6 use crate::lexer::{LexError, Lexer, LocatedError, LocatedToken, Token}; 7 use crate::run_command::{Comparison, Invocation, RunCommand}; 8 use crate::sourcemap::SourceMap; 9 use crate::testcommand::TestCommand; 10 use crate::testfile::{Comment, Details, Feature, TestFile}; 11 use cranelift_codegen::data_value::DataValue; 12 use cranelift_codegen::entity::EntityRef; 13 use cranelift_codegen::ir; 14 use cranelift_codegen::ir::entities::AnyEntity; 15 use cranelift_codegen::ir::immediates::{Ieee32, Ieee64, Imm64, Offset32, Uimm32, Uimm64}; 16 use cranelift_codegen::ir::instructions::{InstructionData, InstructionFormat, VariableArgs}; 17 use cranelift_codegen::ir::types::INVALID; 18 use cranelift_codegen::ir::types::*; 19 use cranelift_codegen::ir::{ 20 AbiParam, ArgumentExtension, ArgumentPurpose, Block, Constant, ConstantData, ExtFuncData, 21 ExternalName, FuncRef, Function, GlobalValue, GlobalValueData, Heap, HeapData, HeapStyle, 22 JumpTable, JumpTableData, MemFlags, Opcode, SigRef, Signature, StackSlot, StackSlotData, 23 StackSlotKind, Table, TableData, Type, Value, 24 }; 25 use cranelift_codegen::isa::{self, CallConv}; 26 use cranelift_codegen::packed_option::ReservedValue; 27 use cranelift_codegen::{settings, settings::Configurable, timing}; 28 use smallvec::SmallVec; 29 use std::mem; 30 use std::str::FromStr; 31 use std::{u16, u32}; 32 use target_lexicon::Triple; 33 34 macro_rules! match_imm { 35 ($signed:ty, $unsigned:ty, $parser:expr, $err_msg:expr) => {{ 36 if let Some(Token::Integer(text)) = $parser.token() { 37 $parser.consume(); 38 let negative = text.starts_with('-'); 39 let positive = text.starts_with('+'); 40 let text = if negative || positive { 41 // Strip sign prefix. 42 &text[1..] 43 } else { 44 text 45 }; 46 47 // Parse the text value; the lexer gives us raw text that looks like an integer. 48 let value = if text.starts_with("0x") { 49 // Skip underscores. 50 let text = text.replace("_", ""); 51 // Parse it in hexadecimal form. 52 <$unsigned>::from_str_radix(&text[2..], 16).map_err(|_| { 53 $parser.error("unable to parse value as a hexadecimal immediate") 54 })? 55 } else { 56 // Parse it as a signed type to check for overflow and other issues. 57 text.parse() 58 .map_err(|_| $parser.error("expected decimal immediate"))? 59 }; 60 61 // Apply sign if necessary. 62 let signed = if negative { 63 let value = value.wrapping_neg() as $signed; 64 if value > 0 { 65 return Err($parser.error("negative number too small")); 66 } 67 value 68 } else { 69 value as $signed 70 }; 71 72 Ok(signed) 73 } else { 74 err!($parser.loc, $err_msg) 75 } 76 }}; 77 } 78 79 /// After some quick benchmarks a program should never have more than 100,000 blocks. 80 const MAX_BLOCKS_IN_A_FUNCTION: u32 = 100_000; 81 82 /// Parse the entire `text` into a list of functions. 83 /// 84 /// Any test commands or target declarations are ignored. 85 pub fn parse_functions(text: &str) -> ParseResult<Vec<Function>> { 86 let _tt = timing::parse_text(); 87 parse_test(text, ParseOptions::default()) 88 .map(|file| file.functions.into_iter().map(|(func, _)| func).collect()) 89 } 90 91 /// Options for configuring the parsing of filetests. 92 pub struct ParseOptions<'a> { 93 /// Compiler passes to run on the parsed functions. 94 pub passes: Option<&'a [String]>, 95 /// Target ISA for compiling the parsed functions, e.g. "x86_64 skylake". 96 pub target: Option<&'a str>, 97 /// Default calling convention used when none is specified for a parsed function. 98 pub default_calling_convention: CallConv, 99 /// Default for unwind-info setting (enabled or disabled). 100 pub unwind_info: bool, 101 } 102 103 impl Default for ParseOptions<'_> { 104 fn default() -> Self { 105 Self { 106 passes: None, 107 target: None, 108 default_calling_convention: CallConv::Fast, 109 unwind_info: false, 110 } 111 } 112 } 113 114 /// Parse the entire `text` as a test case file. 115 /// 116 /// The returned `TestFile` contains direct references to substrings of `text`. 117 pub fn parse_test<'a>(text: &'a str, options: ParseOptions<'a>) -> ParseResult<TestFile<'a>> { 118 let _tt = timing::parse_text(); 119 let mut parser = Parser::new(text); 120 121 // Gather the preamble comments. 122 parser.start_gathering_comments(); 123 124 let isa_spec: isaspec::IsaSpec; 125 let commands: Vec<TestCommand<'a>>; 126 127 // Check for specified passes and target, if present throw out test commands/targets specified 128 // in file. 129 match options.passes { 130 Some(pass_vec) => { 131 parser.parse_test_commands(); 132 commands = parser.parse_cmdline_passes(pass_vec); 133 parser.parse_target_specs(&options)?; 134 isa_spec = parser.parse_cmdline_target(options.target)?; 135 } 136 None => { 137 commands = parser.parse_test_commands(); 138 isa_spec = parser.parse_target_specs(&options)?; 139 } 140 }; 141 let features = parser.parse_cranelift_features()?; 142 143 // Decide between using the calling convention passed in the options or using the 144 // host's calling convention--if any tests are to be run on the host we should default to the 145 // host's calling convention. 146 parser = if commands.iter().any(|tc| tc.command == "run") { 147 let host_default_calling_convention = CallConv::triple_default(&Triple::host()); 148 parser.with_default_calling_convention(host_default_calling_convention) 149 } else { 150 parser.with_default_calling_convention(options.default_calling_convention) 151 }; 152 153 parser.token(); 154 parser.claim_gathered_comments(AnyEntity::Function); 155 156 let preamble_comments = parser.take_comments(); 157 let functions = parser.parse_function_list()?; 158 159 Ok(TestFile { 160 commands, 161 isa_spec, 162 features, 163 preamble_comments, 164 functions, 165 }) 166 } 167 168 /// Parse a CLIF comment `text` as a run command. 169 /// 170 /// Return: 171 /// - `Ok(None)` if the comment is not intended to be a `RunCommand` (i.e. does not start with `run` 172 /// or `print` 173 /// - `Ok(Some(command))` if the comment is intended as a `RunCommand` and can be parsed to one 174 /// - `Err` otherwise. 175 pub fn parse_run_command<'a>(text: &str, signature: &Signature) -> ParseResult<Option<RunCommand>> { 176 let _tt = timing::parse_text(); 177 // We remove leading spaces and semi-colons for convenience here instead of at the call sites 178 // since this function will be attempting to parse a RunCommand from a CLIF comment. 179 let trimmed_text = text.trim_start_matches(|c| c == ' ' || c == ';'); 180 let mut parser = Parser::new(trimmed_text); 181 match parser.token() { 182 Some(Token::Identifier("run")) | Some(Token::Identifier("print")) => { 183 parser.parse_run_command(signature).map(|c| Some(c)) 184 } 185 Some(_) | None => Ok(None), 186 } 187 } 188 189 /// Parse a CLIF comment `text` as a heap command. 190 /// 191 /// Return: 192 /// - `Ok(None)` if the comment is not intended to be a `HeapCommand` (i.e. does not start with `heap` 193 /// - `Ok(Some(heap))` if the comment is intended as a `HeapCommand` and can be parsed to one 194 /// - `Err` otherwise. 195 pub fn parse_heap_command<'a>(text: &str) -> ParseResult<Option<HeapCommand>> { 196 let _tt = timing::parse_text(); 197 // We remove leading spaces and semi-colons for convenience here instead of at the call sites 198 // since this function will be attempting to parse a HeapCommand from a CLIF comment. 199 let trimmed_text = text.trim_start_matches(|c| c == ' ' || c == ';'); 200 let mut parser = Parser::new(trimmed_text); 201 match parser.token() { 202 Some(Token::Identifier("heap")) => parser.parse_heap_command().map(|c| Some(c)), 203 Some(_) | None => Ok(None), 204 } 205 } 206 207 pub struct Parser<'a> { 208 lex: Lexer<'a>, 209 210 lex_error: Option<LexError>, 211 212 /// Current lookahead token. 213 lookahead: Option<Token<'a>>, 214 215 /// Location of lookahead. 216 loc: Location, 217 218 /// Are we gathering any comments that we encounter? 219 gathering_comments: bool, 220 221 /// The gathered comments; claim them with `claim_gathered_comments`. 222 gathered_comments: Vec<&'a str>, 223 224 /// Comments collected so far. 225 comments: Vec<Comment<'a>>, 226 227 /// Default calling conventions; used when none is specified. 228 default_calling_convention: CallConv, 229 } 230 231 /// Context for resolving references when parsing a single function. 232 struct Context { 233 function: Function, 234 map: SourceMap, 235 236 /// Aliases to resolve once value definitions are known. 237 aliases: Vec<Value>, 238 } 239 240 impl Context { 241 fn new(f: Function) -> Self { 242 Self { 243 function: f, 244 map: SourceMap::new(), 245 aliases: Vec::new(), 246 } 247 } 248 249 // Allocate a new stack slot. 250 fn add_ss(&mut self, ss: StackSlot, data: StackSlotData, loc: Location) -> ParseResult<()> { 251 self.map.def_ss(ss, loc)?; 252 while self.function.stack_slots.next_key().index() <= ss.index() { 253 self.function 254 .create_stack_slot(StackSlotData::new(StackSlotKind::ExplicitSlot, 0)); 255 } 256 self.function.stack_slots[ss] = data; 257 Ok(()) 258 } 259 260 // Resolve a reference to a stack slot. 261 fn check_ss(&self, ss: StackSlot, loc: Location) -> ParseResult<()> { 262 if !self.map.contains_ss(ss) { 263 err!(loc, "undefined stack slot {}", ss) 264 } else { 265 Ok(()) 266 } 267 } 268 269 // Allocate a global value slot. 270 fn add_gv(&mut self, gv: GlobalValue, data: GlobalValueData, loc: Location) -> ParseResult<()> { 271 self.map.def_gv(gv, loc)?; 272 while self.function.global_values.next_key().index() <= gv.index() { 273 self.function.create_global_value(GlobalValueData::Symbol { 274 name: ExternalName::testcase(""), 275 offset: Imm64::new(0), 276 colocated: false, 277 tls: false, 278 }); 279 } 280 self.function.global_values[gv] = data; 281 Ok(()) 282 } 283 284 // Resolve a reference to a global value. 285 fn check_gv(&self, gv: GlobalValue, loc: Location) -> ParseResult<()> { 286 if !self.map.contains_gv(gv) { 287 err!(loc, "undefined global value {}", gv) 288 } else { 289 Ok(()) 290 } 291 } 292 293 // Allocate a heap slot. 294 fn add_heap(&mut self, heap: Heap, data: HeapData, loc: Location) -> ParseResult<()> { 295 self.map.def_heap(heap, loc)?; 296 while self.function.heaps.next_key().index() <= heap.index() { 297 self.function.create_heap(HeapData { 298 base: GlobalValue::reserved_value(), 299 min_size: Uimm64::new(0), 300 offset_guard_size: Uimm64::new(0), 301 style: HeapStyle::Static { 302 bound: Uimm64::new(0), 303 }, 304 index_type: INVALID, 305 }); 306 } 307 self.function.heaps[heap] = data; 308 Ok(()) 309 } 310 311 // Resolve a reference to a heap. 312 fn check_heap(&self, heap: Heap, loc: Location) -> ParseResult<()> { 313 if !self.map.contains_heap(heap) { 314 err!(loc, "undefined heap {}", heap) 315 } else { 316 Ok(()) 317 } 318 } 319 320 // Allocate a table slot. 321 fn add_table(&mut self, table: Table, data: TableData, loc: Location) -> ParseResult<()> { 322 while self.function.tables.next_key().index() <= table.index() { 323 self.function.create_table(TableData { 324 base_gv: GlobalValue::reserved_value(), 325 min_size: Uimm64::new(0), 326 bound_gv: GlobalValue::reserved_value(), 327 element_size: Uimm64::new(0), 328 index_type: INVALID, 329 }); 330 } 331 self.function.tables[table] = data; 332 self.map.def_table(table, loc) 333 } 334 335 // Resolve a reference to a table. 336 fn check_table(&self, table: Table, loc: Location) -> ParseResult<()> { 337 if !self.map.contains_table(table) { 338 err!(loc, "undefined table {}", table) 339 } else { 340 Ok(()) 341 } 342 } 343 344 // Allocate a new signature. 345 fn add_sig( 346 &mut self, 347 sig: SigRef, 348 data: Signature, 349 loc: Location, 350 defaultcc: CallConv, 351 ) -> ParseResult<()> { 352 self.map.def_sig(sig, loc)?; 353 while self.function.dfg.signatures.next_key().index() <= sig.index() { 354 self.function.import_signature(Signature::new(defaultcc)); 355 } 356 self.function.dfg.signatures[sig] = data; 357 Ok(()) 358 } 359 360 // Resolve a reference to a signature. 361 fn check_sig(&self, sig: SigRef, loc: Location) -> ParseResult<()> { 362 if !self.map.contains_sig(sig) { 363 err!(loc, "undefined signature {}", sig) 364 } else { 365 Ok(()) 366 } 367 } 368 369 // Allocate a new external function. 370 fn add_fn(&mut self, fn_: FuncRef, data: ExtFuncData, loc: Location) -> ParseResult<()> { 371 self.map.def_fn(fn_, loc)?; 372 while self.function.dfg.ext_funcs.next_key().index() <= fn_.index() { 373 self.function.import_function(ExtFuncData { 374 name: ExternalName::testcase(""), 375 signature: SigRef::reserved_value(), 376 colocated: false, 377 }); 378 } 379 self.function.dfg.ext_funcs[fn_] = data; 380 Ok(()) 381 } 382 383 // Resolve a reference to a function. 384 fn check_fn(&self, fn_: FuncRef, loc: Location) -> ParseResult<()> { 385 if !self.map.contains_fn(fn_) { 386 err!(loc, "undefined function {}", fn_) 387 } else { 388 Ok(()) 389 } 390 } 391 392 // Allocate a new jump table. 393 fn add_jt(&mut self, jt: JumpTable, data: JumpTableData, loc: Location) -> ParseResult<()> { 394 self.map.def_jt(jt, loc)?; 395 while self.function.jump_tables.next_key().index() <= jt.index() { 396 self.function.create_jump_table(JumpTableData::new()); 397 } 398 self.function.jump_tables[jt] = data; 399 Ok(()) 400 } 401 402 // Resolve a reference to a jump table. 403 fn check_jt(&self, jt: JumpTable, loc: Location) -> ParseResult<()> { 404 if !self.map.contains_jt(jt) { 405 err!(loc, "undefined jump table {}", jt) 406 } else { 407 Ok(()) 408 } 409 } 410 411 // Allocate a new constant. 412 fn add_constant( 413 &mut self, 414 constant: Constant, 415 data: ConstantData, 416 loc: Location, 417 ) -> ParseResult<()> { 418 self.map.def_constant(constant, loc)?; 419 self.function.dfg.constants.set(constant, data); 420 Ok(()) 421 } 422 423 // Configure the stack limit of the current function. 424 fn add_stack_limit(&mut self, limit: GlobalValue, loc: Location) -> ParseResult<()> { 425 if self.function.stack_limit.is_some() { 426 return err!(loc, "stack limit defined twice"); 427 } 428 self.function.stack_limit = Some(limit); 429 Ok(()) 430 } 431 432 // Resolve a reference to a constant. 433 fn check_constant(&self, c: Constant, loc: Location) -> ParseResult<()> { 434 if !self.map.contains_constant(c) { 435 err!(loc, "undefined constant {}", c) 436 } else { 437 Ok(()) 438 } 439 } 440 441 // Allocate a new block. 442 fn add_block(&mut self, block: Block, loc: Location) -> ParseResult<Block> { 443 self.map.def_block(block, loc)?; 444 while self.function.dfg.num_blocks() <= block.index() { 445 self.function.dfg.make_block(); 446 } 447 self.function.layout.append_block(block); 448 Ok(block) 449 } 450 451 /// Set a block as cold. 452 fn set_cold_block(&mut self, block: Block) { 453 self.function.layout.set_cold(block); 454 } 455 } 456 457 impl<'a> Parser<'a> { 458 /// Create a new `Parser` which reads `text`. The referenced text must outlive the parser. 459 pub fn new(text: &'a str) -> Self { 460 Self { 461 lex: Lexer::new(text), 462 lex_error: None, 463 lookahead: None, 464 loc: Location { line_number: 0 }, 465 gathering_comments: false, 466 gathered_comments: Vec::new(), 467 comments: Vec::new(), 468 default_calling_convention: CallConv::Fast, 469 } 470 } 471 472 /// Modify the default calling convention; returns a new parser with the changed calling 473 /// convention. 474 pub fn with_default_calling_convention(self, default_calling_convention: CallConv) -> Self { 475 Self { 476 default_calling_convention, 477 ..self 478 } 479 } 480 481 // Consume the current lookahead token and return it. 482 fn consume(&mut self) -> Token<'a> { 483 self.lookahead.take().expect("No token to consume") 484 } 485 486 // Consume the whole line following the current lookahead token. 487 // Return the text of the line tail. 488 fn consume_line(&mut self) -> &'a str { 489 let rest = self.lex.rest_of_line(); 490 self.consume(); 491 rest 492 } 493 494 // Get the current lookahead token, after making sure there is one. 495 fn token(&mut self) -> Option<Token<'a>> { 496 // clippy says self.lookahead is immutable so this loop is either infinite or never 497 // running. I don't think this is true - self.lookahead is mutated in the loop body - so 498 // maybe this is a clippy bug? Either way, disable clippy for this. 499 #[cfg_attr(feature = "cargo-clippy", allow(clippy::while_immutable_condition))] 500 while self.lookahead.is_none() { 501 match self.lex.next() { 502 Some(Ok(LocatedToken { token, location })) => { 503 match token { 504 Token::Comment(text) => { 505 if self.gathering_comments { 506 self.gathered_comments.push(text); 507 } 508 } 509 _ => self.lookahead = Some(token), 510 } 511 self.loc = location; 512 } 513 Some(Err(LocatedError { error, location })) => { 514 self.lex_error = Some(error); 515 self.loc = location; 516 break; 517 } 518 None => break, 519 } 520 } 521 self.lookahead 522 } 523 524 // Enable gathering of all comments encountered. 525 fn start_gathering_comments(&mut self) { 526 debug_assert!(!self.gathering_comments); 527 self.gathering_comments = true; 528 debug_assert!(self.gathered_comments.is_empty()); 529 } 530 531 // Claim the comments gathered up to the current position for the 532 // given entity. 533 fn claim_gathered_comments<E: Into<AnyEntity>>(&mut self, entity: E) { 534 debug_assert!(self.gathering_comments); 535 let entity = entity.into(); 536 self.comments.extend( 537 self.gathered_comments 538 .drain(..) 539 .map(|text| Comment { entity, text }), 540 ); 541 self.gathering_comments = false; 542 } 543 544 // Get the comments collected so far, clearing out the internal list. 545 fn take_comments(&mut self) -> Vec<Comment<'a>> { 546 debug_assert!(!self.gathering_comments); 547 mem::replace(&mut self.comments, Vec::new()) 548 } 549 550 // Match and consume a token without payload. 551 fn match_token(&mut self, want: Token<'a>, err_msg: &str) -> ParseResult<Token<'a>> { 552 if self.token() == Some(want) { 553 Ok(self.consume()) 554 } else { 555 err!(self.loc, err_msg) 556 } 557 } 558 559 // If the next token is a `want`, consume it, otherwise do nothing. 560 fn optional(&mut self, want: Token<'a>) -> bool { 561 if self.token() == Some(want) { 562 self.consume(); 563 true 564 } else { 565 false 566 } 567 } 568 569 // Match and consume a specific identifier string. 570 // Used for pseudo-keywords like "stack_slot" that only appear in certain contexts. 571 fn match_identifier(&mut self, want: &'static str, err_msg: &str) -> ParseResult<Token<'a>> { 572 if self.token() == Some(Token::Identifier(want)) { 573 Ok(self.consume()) 574 } else { 575 err!(self.loc, err_msg) 576 } 577 } 578 579 // Match and consume a type. 580 fn match_type(&mut self, err_msg: &str) -> ParseResult<Type> { 581 if let Some(Token::Type(t)) = self.token() { 582 self.consume(); 583 Ok(t) 584 } else { 585 err!(self.loc, err_msg) 586 } 587 } 588 589 // Match and consume a stack slot reference. 590 fn match_ss(&mut self, err_msg: &str) -> ParseResult<StackSlot> { 591 if let Some(Token::StackSlot(ss)) = self.token() { 592 self.consume(); 593 if let Some(ss) = StackSlot::with_number(ss) { 594 return Ok(ss); 595 } 596 } 597 err!(self.loc, err_msg) 598 } 599 600 // Match and consume a global value reference. 601 fn match_gv(&mut self, err_msg: &str) -> ParseResult<GlobalValue> { 602 if let Some(Token::GlobalValue(gv)) = self.token() { 603 self.consume(); 604 if let Some(gv) = GlobalValue::with_number(gv) { 605 return Ok(gv); 606 } 607 } 608 err!(self.loc, err_msg) 609 } 610 611 // Match and consume a function reference. 612 fn match_fn(&mut self, err_msg: &str) -> ParseResult<FuncRef> { 613 if let Some(Token::FuncRef(fnref)) = self.token() { 614 self.consume(); 615 if let Some(fnref) = FuncRef::with_number(fnref) { 616 return Ok(fnref); 617 } 618 } 619 err!(self.loc, err_msg) 620 } 621 622 // Match and consume a signature reference. 623 fn match_sig(&mut self, err_msg: &str) -> ParseResult<SigRef> { 624 if let Some(Token::SigRef(sigref)) = self.token() { 625 self.consume(); 626 if let Some(sigref) = SigRef::with_number(sigref) { 627 return Ok(sigref); 628 } 629 } 630 err!(self.loc, err_msg) 631 } 632 633 // Match and consume a heap reference. 634 fn match_heap(&mut self, err_msg: &str) -> ParseResult<Heap> { 635 if let Some(Token::Heap(heap)) = self.token() { 636 self.consume(); 637 if let Some(heap) = Heap::with_number(heap) { 638 return Ok(heap); 639 } 640 } 641 err!(self.loc, err_msg) 642 } 643 644 // Match and consume a table reference. 645 fn match_table(&mut self, err_msg: &str) -> ParseResult<Table> { 646 if let Some(Token::Table(table)) = self.token() { 647 self.consume(); 648 if let Some(table) = Table::with_number(table) { 649 return Ok(table); 650 } 651 } 652 err!(self.loc, err_msg) 653 } 654 655 // Match and consume a jump table reference. 656 fn match_jt(&mut self) -> ParseResult<JumpTable> { 657 if let Some(Token::JumpTable(jt)) = self.token() { 658 self.consume(); 659 if let Some(jt) = JumpTable::with_number(jt) { 660 return Ok(jt); 661 } 662 } 663 err!(self.loc, "expected jump table number: jt«n»") 664 } 665 666 // Match and consume a constant reference. 667 fn match_constant(&mut self) -> ParseResult<Constant> { 668 if let Some(Token::Constant(c)) = self.token() { 669 self.consume(); 670 if let Some(c) = Constant::with_number(c) { 671 return Ok(c); 672 } 673 } 674 err!(self.loc, "expected constant number: const«n»") 675 } 676 677 // Match and consume a stack limit token 678 fn match_stack_limit(&mut self) -> ParseResult<()> { 679 if let Some(Token::Identifier("stack_limit")) = self.token() { 680 self.consume(); 681 return Ok(()); 682 } 683 err!(self.loc, "expected identifier: stack_limit") 684 } 685 686 // Match and consume a block reference. 687 fn match_block(&mut self, err_msg: &str) -> ParseResult<Block> { 688 if let Some(Token::Block(block)) = self.token() { 689 self.consume(); 690 Ok(block) 691 } else { 692 err!(self.loc, err_msg) 693 } 694 } 695 696 // Match and consume a value reference. 697 fn match_value(&mut self, err_msg: &str) -> ParseResult<Value> { 698 if let Some(Token::Value(v)) = self.token() { 699 self.consume(); 700 Ok(v) 701 } else { 702 err!(self.loc, err_msg) 703 } 704 } 705 706 fn error(&self, message: &str) -> ParseError { 707 ParseError { 708 location: self.loc, 709 message: message.to_string(), 710 is_warning: false, 711 } 712 } 713 714 // Match and consume an Imm64 immediate. 715 fn match_imm64(&mut self, err_msg: &str) -> ParseResult<Imm64> { 716 if let Some(Token::Integer(text)) = self.token() { 717 self.consume(); 718 // Lexer just gives us raw text that looks like an integer. 719 // Parse it as an Imm64 to check for overflow and other issues. 720 text.parse().map_err(|e| self.error(e)) 721 } else { 722 err!(self.loc, err_msg) 723 } 724 } 725 726 // Match and consume a hexadeximal immediate 727 fn match_hexadecimal_constant(&mut self, err_msg: &str) -> ParseResult<ConstantData> { 728 if let Some(Token::Integer(text)) = self.token() { 729 self.consume(); 730 text.parse().map_err(|e| { 731 self.error(&format!( 732 "expected hexadecimal immediate, failed to parse: {}", 733 e 734 )) 735 }) 736 } else { 737 err!(self.loc, err_msg) 738 } 739 } 740 741 // Match and consume a sequence of immediate bytes (uimm8); e.g. [0x42 0x99 0x32] 742 fn match_constant_data(&mut self) -> ParseResult<ConstantData> { 743 self.match_token(Token::LBracket, "expected an opening left bracket")?; 744 let mut data = ConstantData::default(); 745 while !self.optional(Token::RBracket) { 746 data = data.append(self.match_uimm8("expected a sequence of bytes (uimm8)")?); 747 } 748 Ok(data) 749 } 750 751 // Match and consume either a hexadecimal Uimm128 immediate (e.g. 0x000102...) or its literal 752 // list form (e.g. [0 1 2...]). For convenience, since uimm128 values are stored in the 753 // `ConstantPool`, this returns `ConstantData`. 754 fn match_uimm128(&mut self, controlling_type: Type) -> ParseResult<ConstantData> { 755 let expected_size = controlling_type.bytes() as usize; 756 let constant_data = if self.optional(Token::LBracket) { 757 // parse using a list of values, e.g. vconst.i32x4 [0 1 2 3] 758 let uimm128 = self.parse_literals_to_constant_data(controlling_type)?; 759 self.match_token(Token::RBracket, "expected a terminating right bracket")?; 760 uimm128 761 } else { 762 // parse using a hexadecimal value, e.g. 0x000102... 763 let uimm128 = 764 self.match_hexadecimal_constant("expected an immediate hexadecimal operand")?; 765 uimm128.expand_to(expected_size) 766 }; 767 768 if constant_data.len() == expected_size { 769 Ok(constant_data) 770 } else { 771 Err(self.error(&format!( 772 "expected parsed constant to have {} bytes", 773 expected_size 774 ))) 775 } 776 } 777 778 // Match and consume a Uimm64 immediate. 779 fn match_uimm64(&mut self, err_msg: &str) -> ParseResult<Uimm64> { 780 if let Some(Token::Integer(text)) = self.token() { 781 self.consume(); 782 // Lexer just gives us raw text that looks like an integer. 783 // Parse it as an Uimm64 to check for overflow and other issues. 784 text.parse() 785 .map_err(|_| self.error("expected u64 decimal immediate")) 786 } else { 787 err!(self.loc, err_msg) 788 } 789 } 790 791 // Match and consume a Uimm32 immediate. 792 fn match_uimm32(&mut self, err_msg: &str) -> ParseResult<Uimm32> { 793 if let Some(Token::Integer(text)) = self.token() { 794 self.consume(); 795 // Lexer just gives us raw text that looks like an integer. 796 // Parse it as an Uimm32 to check for overflow and other issues. 797 text.parse().map_err(|e| self.error(e)) 798 } else { 799 err!(self.loc, err_msg) 800 } 801 } 802 803 // Match and consume a u8 immediate. 804 // This is used for lane numbers in SIMD vectors. 805 fn match_uimm8(&mut self, err_msg: &str) -> ParseResult<u8> { 806 if let Some(Token::Integer(text)) = self.token() { 807 self.consume(); 808 // Lexer just gives us raw text that looks like an integer. 809 if text.starts_with("0x") { 810 // Parse it as a u8 in hexadecimal form. 811 u8::from_str_radix(&text[2..], 16) 812 .map_err(|_| self.error("unable to parse u8 as a hexadecimal immediate")) 813 } else { 814 // Parse it as a u8 to check for overflow and other issues. 815 text.parse() 816 .map_err(|_| self.error("expected u8 decimal immediate")) 817 } 818 } else { 819 err!(self.loc, err_msg) 820 } 821 } 822 823 // Match and consume an i8 immediate. 824 fn match_imm8(&mut self, err_msg: &str) -> ParseResult<i8> { 825 match_imm!(i8, u8, self, err_msg) 826 } 827 828 // Match and consume a signed 16-bit immediate. 829 fn match_imm16(&mut self, err_msg: &str) -> ParseResult<i16> { 830 match_imm!(i16, u16, self, err_msg) 831 } 832 833 // Match and consume an i32 immediate. 834 // This is used for stack argument byte offsets. 835 fn match_imm32(&mut self, err_msg: &str) -> ParseResult<i32> { 836 match_imm!(i32, u32, self, err_msg) 837 } 838 839 // Match and consume an i128 immediate. 840 fn match_imm128(&mut self, err_msg: &str) -> ParseResult<i128> { 841 match_imm!(i128, u128, self, err_msg) 842 } 843 844 // Match and consume an optional offset32 immediate. 845 // 846 // Note that this will match an empty string as an empty offset, and that if an offset is 847 // present, it must contain a sign. 848 fn optional_offset32(&mut self) -> ParseResult<Offset32> { 849 if let Some(Token::Integer(text)) = self.token() { 850 if text.starts_with('+') || text.starts_with('-') { 851 self.consume(); 852 // Lexer just gives us raw text that looks like an integer. 853 // Parse it as an `Offset32` to check for overflow and other issues. 854 return text.parse().map_err(|e| self.error(e)); 855 } 856 } 857 // An offset32 operand can be absent. 858 Ok(Offset32::new(0)) 859 } 860 861 // Match and consume an optional offset32 immediate. 862 // 863 // Note that this will match an empty string as an empty offset, and that if an offset is 864 // present, it must contain a sign. 865 fn optional_offset_imm64(&mut self) -> ParseResult<Imm64> { 866 if let Some(Token::Integer(text)) = self.token() { 867 if text.starts_with('+') || text.starts_with('-') { 868 self.consume(); 869 // Lexer just gives us raw text that looks like an integer. 870 // Parse it as an `Offset32` to check for overflow and other issues. 871 return text.parse().map_err(|e| self.error(e)); 872 } 873 } 874 // If no explicit offset is present, the offset is 0. 875 Ok(Imm64::new(0)) 876 } 877 878 // Match and consume an Ieee32 immediate. 879 fn match_ieee32(&mut self, err_msg: &str) -> ParseResult<Ieee32> { 880 if let Some(Token::Float(text)) = self.token() { 881 self.consume(); 882 // Lexer just gives us raw text that looks like a float. 883 // Parse it as an Ieee32 to check for the right number of digits and other issues. 884 text.parse().map_err(|e| self.error(e)) 885 } else { 886 err!(self.loc, err_msg) 887 } 888 } 889 890 // Match and consume an Ieee64 immediate. 891 fn match_ieee64(&mut self, err_msg: &str) -> ParseResult<Ieee64> { 892 if let Some(Token::Float(text)) = self.token() { 893 self.consume(); 894 // Lexer just gives us raw text that looks like a float. 895 // Parse it as an Ieee64 to check for the right number of digits and other issues. 896 text.parse().map_err(|e| self.error(e)) 897 } else { 898 err!(self.loc, err_msg) 899 } 900 } 901 902 // Match and consume a boolean immediate. 903 fn match_bool(&mut self, err_msg: &str) -> ParseResult<bool> { 904 if let Some(Token::Identifier(text)) = self.token() { 905 self.consume(); 906 match text { 907 "true" => Ok(true), 908 "false" => Ok(false), 909 _ => err!(self.loc, err_msg), 910 } 911 } else { 912 err!(self.loc, err_msg) 913 } 914 } 915 916 // Match and consume an enumerated immediate, like one of the condition codes. 917 fn match_enum<T: FromStr>(&mut self, err_msg: &str) -> ParseResult<T> { 918 if let Some(Token::Identifier(text)) = self.token() { 919 self.consume(); 920 text.parse().map_err(|_| self.error(err_msg)) 921 } else { 922 err!(self.loc, err_msg) 923 } 924 } 925 926 // Match and a consume a possibly empty sequence of memory operation flags. 927 fn optional_memflags(&mut self) -> MemFlags { 928 let mut flags = MemFlags::new(); 929 while let Some(Token::Identifier(text)) = self.token() { 930 if flags.set_by_name(text) { 931 self.consume(); 932 } else { 933 break; 934 } 935 } 936 flags 937 } 938 939 // Match and consume an identifier. 940 fn match_any_identifier(&mut self, err_msg: &str) -> ParseResult<&'a str> { 941 if let Some(Token::Identifier(text)) = self.token() { 942 self.consume(); 943 Ok(text) 944 } else { 945 err!(self.loc, err_msg) 946 } 947 } 948 949 /// Parse an optional source location. 950 /// 951 /// Return an optional source location if no real location is present. 952 fn optional_srcloc(&mut self) -> ParseResult<ir::SourceLoc> { 953 if let Some(Token::SourceLoc(text)) = self.token() { 954 match u32::from_str_radix(text, 16) { 955 Ok(num) => { 956 self.consume(); 957 Ok(ir::SourceLoc::new(num)) 958 } 959 Err(_) => return err!(self.loc, "invalid source location: {}", text), 960 } 961 } else { 962 Ok(Default::default()) 963 } 964 } 965 966 /// Parse a list of literals (i.e. integers, floats, booleans); e.g. `0 1 2 3`, usually as 967 /// part of something like `vconst.i32x4 [0 1 2 3]`. 968 fn parse_literals_to_constant_data(&mut self, ty: Type) -> ParseResult<ConstantData> { 969 macro_rules! consume { 970 ( $ty:ident, $match_fn:expr ) => {{ 971 assert!($ty.is_vector()); 972 let mut data = ConstantData::default(); 973 for _ in 0..$ty.lane_count() { 974 data = data.append($match_fn); 975 } 976 data 977 }}; 978 } 979 980 fn boolean_to_vec(value: bool, ty: Type) -> Vec<u8> { 981 let lane_size = ty.bytes() / u32::from(ty.lane_count()); 982 if lane_size < 1 { 983 panic!("The boolean lane must have a byte size greater than zero."); 984 } 985 let value = if value { 0xFF } else { 0 }; 986 vec![value; lane_size as usize] 987 } 988 989 if !ty.is_vector() { 990 err!(self.loc, "Expected a controlling vector type, not {}", ty) 991 } else { 992 let constant_data = match ty.lane_type() { 993 I8 => consume!(ty, self.match_imm8("Expected an 8-bit integer")?), 994 I16 => consume!(ty, self.match_imm16("Expected a 16-bit integer")?), 995 I32 => consume!(ty, self.match_imm32("Expected a 32-bit integer")?), 996 I64 => consume!(ty, self.match_imm64("Expected a 64-bit integer")?), 997 F32 => consume!(ty, self.match_ieee32("Expected a 32-bit float")?), 998 F64 => consume!(ty, self.match_ieee64("Expected a 64-bit float")?), 999 b if b.is_bool() => consume!( 1000 ty, 1001 boolean_to_vec(self.match_bool("Expected a boolean")?, ty) 1002 ), 1003 _ => return err!(self.loc, "Expected a type of: float, int, bool"), 1004 }; 1005 Ok(constant_data) 1006 } 1007 } 1008 1009 /// Parse a list of test command passes specified in command line. 1010 pub fn parse_cmdline_passes(&mut self, passes: &'a [String]) -> Vec<TestCommand<'a>> { 1011 let mut list = Vec::new(); 1012 for pass in passes { 1013 list.push(TestCommand::new(pass)); 1014 } 1015 list 1016 } 1017 1018 /// Parse a list of test commands. 1019 pub fn parse_test_commands(&mut self) -> Vec<TestCommand<'a>> { 1020 let mut list = Vec::new(); 1021 while self.token() == Some(Token::Identifier("test")) { 1022 list.push(TestCommand::new(self.consume_line())); 1023 } 1024 list 1025 } 1026 1027 /// Parse a target spec. 1028 /// 1029 /// Accept the target from the command line for pass command. 1030 /// 1031 fn parse_cmdline_target(&mut self, target_pass: Option<&str>) -> ParseResult<isaspec::IsaSpec> { 1032 // Were there any `target` commands specified? 1033 let mut specified_target = false; 1034 1035 let mut targets = Vec::new(); 1036 let flag_builder = settings::builder(); 1037 1038 if let Some(targ) = target_pass { 1039 let loc = self.loc; 1040 let triple = match Triple::from_str(targ) { 1041 Ok(triple) => triple, 1042 Err(err) => return err!(loc, err), 1043 }; 1044 let isa_builder = match isa::lookup(triple) { 1045 Err(isa::LookupError::SupportDisabled) => { 1046 return err!(loc, "support disabled target '{}'", targ); 1047 } 1048 Err(isa::LookupError::Unsupported) => { 1049 return warn!(loc, "unsupported target '{}'", targ); 1050 } 1051 Ok(b) => b, 1052 }; 1053 specified_target = true; 1054 1055 // Construct a trait object with the aggregate settings. 1056 targets.push(isa_builder.finish(settings::Flags::new(flag_builder.clone()))); 1057 } 1058 1059 if !specified_target { 1060 // No `target` commands. 1061 Ok(isaspec::IsaSpec::None(settings::Flags::new(flag_builder))) 1062 } else { 1063 Ok(isaspec::IsaSpec::Some(targets)) 1064 } 1065 } 1066 1067 /// Parse a list of target specs. 1068 /// 1069 /// Accept a mix of `target` and `set` command lines. The `set` commands are cumulative. 1070 /// 1071 fn parse_target_specs(&mut self, options: &ParseOptions) -> ParseResult<isaspec::IsaSpec> { 1072 // Were there any `target` commands? 1073 let mut seen_target = false; 1074 // Location of last `set` command since the last `target`. 1075 let mut last_set_loc = None; 1076 1077 let mut targets = Vec::new(); 1078 let mut flag_builder = settings::builder(); 1079 1080 let unwind_info = if options.unwind_info { "true" } else { "false" }; 1081 flag_builder 1082 .set("unwind_info", unwind_info) 1083 .expect("unwind_info option should be present"); 1084 1085 while let Some(Token::Identifier(command)) = self.token() { 1086 match command { 1087 "set" => { 1088 last_set_loc = Some(self.loc); 1089 isaspec::parse_options( 1090 self.consume_line().trim().split_whitespace(), 1091 &mut flag_builder, 1092 self.loc, 1093 ) 1094 .map_err(|err| ParseError::from(err))?; 1095 } 1096 "target" => { 1097 let loc = self.loc; 1098 // Grab the whole line so the lexer won't go looking for tokens on the 1099 // following lines. 1100 let mut words = self.consume_line().trim().split_whitespace().peekable(); 1101 // Look for `target foo`. 1102 let target_name = match words.next() { 1103 Some(w) => w, 1104 None => return err!(loc, "expected target triple"), 1105 }; 1106 let triple = match Triple::from_str(target_name) { 1107 Ok(triple) => triple, 1108 Err(err) => return err!(loc, err), 1109 }; 1110 let mut isa_builder = match isa::lookup(triple) { 1111 Err(isa::LookupError::SupportDisabled) => { 1112 continue; 1113 } 1114 Err(isa::LookupError::Unsupported) => { 1115 return warn!(loc, "unsupported target '{}'", target_name); 1116 } 1117 Ok(b) => b, 1118 }; 1119 last_set_loc = None; 1120 seen_target = true; 1121 // Apply the target-specific settings to `isa_builder`. 1122 isaspec::parse_options(words, &mut isa_builder, self.loc)?; 1123 1124 // Construct a trait object with the aggregate settings. 1125 targets.push(isa_builder.finish(settings::Flags::new(flag_builder.clone()))); 1126 } 1127 _ => break, 1128 } 1129 } 1130 1131 if !seen_target { 1132 // No `target` commands, but we allow for `set` commands. 1133 Ok(isaspec::IsaSpec::None(settings::Flags::new(flag_builder))) 1134 } else if let Some(loc) = last_set_loc { 1135 err!( 1136 loc, 1137 "dangling 'set' command after ISA specification has no effect." 1138 ) 1139 } else { 1140 Ok(isaspec::IsaSpec::Some(targets)) 1141 } 1142 } 1143 1144 /// Parse a list of expected features that Cranelift should be compiled with, or without. 1145 pub fn parse_cranelift_features(&mut self) -> ParseResult<Vec<Feature<'a>>> { 1146 let mut list = Vec::new(); 1147 while self.token() == Some(Token::Identifier("feature")) { 1148 self.consume(); 1149 let has = !self.optional(Token::Not); 1150 match (self.token(), has) { 1151 (Some(Token::String(flag)), true) => list.push(Feature::With(flag)), 1152 (Some(Token::String(flag)), false) => list.push(Feature::Without(flag)), 1153 (tok, _) => { 1154 return err!( 1155 self.loc, 1156 format!("Expected feature flag string, got {:?}", tok) 1157 ) 1158 } 1159 } 1160 self.consume(); 1161 } 1162 Ok(list) 1163 } 1164 1165 /// Parse a list of function definitions. 1166 /// 1167 /// This is the top-level parse function matching the whole contents of a file. 1168 pub fn parse_function_list(&mut self) -> ParseResult<Vec<(Function, Details<'a>)>> { 1169 let mut list = Vec::new(); 1170 while self.token().is_some() { 1171 list.push(self.parse_function()?); 1172 } 1173 if let Some(err) = self.lex_error { 1174 return match err { 1175 LexError::InvalidChar => err!(self.loc, "invalid character"), 1176 }; 1177 } 1178 Ok(list) 1179 } 1180 1181 // Parse a whole function definition. 1182 // 1183 // function ::= * "function" name signature "{" preamble function-body "}" 1184 // 1185 fn parse_function(&mut self) -> ParseResult<(Function, Details<'a>)> { 1186 // Begin gathering comments. 1187 // Make sure we don't include any comments before the `function` keyword. 1188 self.token(); 1189 debug_assert!(self.comments.is_empty()); 1190 self.start_gathering_comments(); 1191 1192 self.match_identifier("function", "expected 'function'")?; 1193 1194 let location = self.loc; 1195 1196 // function ::= "function" * name signature "{" preamble function-body "}" 1197 let name = self.parse_external_name()?; 1198 1199 // function ::= "function" name * signature "{" preamble function-body "}" 1200 let sig = self.parse_signature()?; 1201 1202 let mut ctx = Context::new(Function::with_name_signature(name, sig)); 1203 1204 // function ::= "function" name signature * "{" preamble function-body "}" 1205 self.match_token(Token::LBrace, "expected '{' before function body")?; 1206 1207 self.token(); 1208 self.claim_gathered_comments(AnyEntity::Function); 1209 1210 // function ::= "function" name signature "{" * preamble function-body "}" 1211 self.parse_preamble(&mut ctx)?; 1212 // function ::= "function" name signature "{" preamble * function-body "}" 1213 self.parse_function_body(&mut ctx)?; 1214 // function ::= "function" name signature "{" preamble function-body * "}" 1215 self.match_token(Token::RBrace, "expected '}' after function body")?; 1216 1217 // Collect any comments following the end of the function, then stop gathering comments. 1218 self.start_gathering_comments(); 1219 self.token(); 1220 self.claim_gathered_comments(AnyEntity::Function); 1221 1222 let details = Details { 1223 location, 1224 comments: self.take_comments(), 1225 map: ctx.map, 1226 }; 1227 1228 Ok((ctx.function, details)) 1229 } 1230 1231 // Parse an external name. 1232 // 1233 // For example, in a function decl, the parser would be in this state: 1234 // 1235 // function ::= "function" * name signature { ... } 1236 // 1237 fn parse_external_name(&mut self) -> ParseResult<ExternalName> { 1238 match self.token() { 1239 Some(Token::Name(s)) => { 1240 self.consume(); 1241 s.parse() 1242 .map_err(|_| self.error("invalid test case or libcall name")) 1243 } 1244 Some(Token::UserRef(namespace)) => { 1245 self.consume(); 1246 match self.token() { 1247 Some(Token::Colon) => { 1248 self.consume(); 1249 match self.token() { 1250 Some(Token::Integer(index_str)) => { 1251 let index: u32 = 1252 u32::from_str_radix(index_str, 10).map_err(|_| { 1253 self.error("the integer given overflows the u32 type") 1254 })?; 1255 self.consume(); 1256 Ok(ExternalName::user(namespace, index)) 1257 } 1258 _ => err!(self.loc, "expected integer"), 1259 } 1260 } 1261 _ => err!(self.loc, "expected colon"), 1262 } 1263 } 1264 _ => err!(self.loc, "expected external name"), 1265 } 1266 } 1267 1268 // Parse a function signature. 1269 // 1270 // signature ::= * "(" [paramlist] ")" ["->" retlist] [callconv] 1271 // 1272 fn parse_signature(&mut self) -> ParseResult<Signature> { 1273 // Calling convention defaults to `fast`, but can be changed. 1274 let mut sig = Signature::new(self.default_calling_convention); 1275 1276 self.match_token(Token::LPar, "expected function signature: ( args... )")?; 1277 // signature ::= "(" * [abi-param-list] ")" ["->" retlist] [callconv] 1278 if self.token() != Some(Token::RPar) { 1279 sig.params = self.parse_abi_param_list()?; 1280 } 1281 self.match_token(Token::RPar, "expected ')' after function arguments")?; 1282 if self.optional(Token::Arrow) { 1283 sig.returns = self.parse_abi_param_list()?; 1284 } 1285 1286 // The calling convention is optional. 1287 if let Some(Token::Identifier(text)) = self.token() { 1288 match text.parse() { 1289 Ok(cc) => { 1290 self.consume(); 1291 sig.call_conv = cc; 1292 } 1293 _ => return err!(self.loc, "unknown calling convention: {}", text), 1294 } 1295 } 1296 1297 Ok(sig) 1298 } 1299 1300 // Parse list of function parameter / return value types. 1301 // 1302 // paramlist ::= * param { "," param } 1303 // 1304 fn parse_abi_param_list(&mut self) -> ParseResult<Vec<AbiParam>> { 1305 let mut list = Vec::new(); 1306 1307 // abi-param-list ::= * abi-param { "," abi-param } 1308 list.push(self.parse_abi_param()?); 1309 1310 // abi-param-list ::= abi-param * { "," abi-param } 1311 while self.optional(Token::Comma) { 1312 // abi-param-list ::= abi-param { "," * abi-param } 1313 list.push(self.parse_abi_param()?); 1314 } 1315 1316 Ok(list) 1317 } 1318 1319 // Parse a single argument type with flags. 1320 fn parse_abi_param(&mut self) -> ParseResult<AbiParam> { 1321 // abi-param ::= * type { flag } [ argumentloc ] 1322 let mut arg = AbiParam::new(self.match_type("expected parameter type")?); 1323 1324 // abi-param ::= type * { flag } [ argumentloc ] 1325 while let Some(Token::Identifier(s)) = self.token() { 1326 match s { 1327 "uext" => arg.extension = ArgumentExtension::Uext, 1328 "sext" => arg.extension = ArgumentExtension::Sext, 1329 "sarg" => { 1330 self.consume(); 1331 self.match_token(Token::LPar, "expected '(' to begin sarg size")?; 1332 let size = self.match_uimm32("expected byte-size in sarg decl")?; 1333 self.match_token(Token::RPar, "expected ')' to end sarg size")?; 1334 arg.purpose = ArgumentPurpose::StructArgument(size.into()); 1335 continue; 1336 } 1337 _ => { 1338 if let Ok(purpose) = s.parse() { 1339 arg.purpose = purpose; 1340 } else { 1341 break; 1342 } 1343 } 1344 } 1345 self.consume(); 1346 } 1347 1348 Ok(arg) 1349 } 1350 1351 // Parse the function preamble. 1352 // 1353 // preamble ::= * { preamble-decl } 1354 // preamble-decl ::= * stack-slot-decl 1355 // * function-decl 1356 // * signature-decl 1357 // * jump-table-decl 1358 // * stack-limit-decl 1359 // 1360 // The parsed decls are added to `ctx` rather than returned. 1361 fn parse_preamble(&mut self, ctx: &mut Context) -> ParseResult<()> { 1362 loop { 1363 match self.token() { 1364 Some(Token::StackSlot(..)) => { 1365 self.start_gathering_comments(); 1366 let loc = self.loc; 1367 self.parse_stack_slot_decl() 1368 .and_then(|(ss, dat)| ctx.add_ss(ss, dat, loc)) 1369 } 1370 Some(Token::GlobalValue(..)) => { 1371 self.start_gathering_comments(); 1372 self.parse_global_value_decl() 1373 .and_then(|(gv, dat)| ctx.add_gv(gv, dat, self.loc)) 1374 } 1375 Some(Token::Heap(..)) => { 1376 self.start_gathering_comments(); 1377 self.parse_heap_decl() 1378 .and_then(|(heap, dat)| ctx.add_heap(heap, dat, self.loc)) 1379 } 1380 Some(Token::Table(..)) => { 1381 self.start_gathering_comments(); 1382 self.parse_table_decl() 1383 .and_then(|(table, dat)| ctx.add_table(table, dat, self.loc)) 1384 } 1385 Some(Token::SigRef(..)) => { 1386 self.start_gathering_comments(); 1387 self.parse_signature_decl().and_then(|(sig, dat)| { 1388 ctx.add_sig(sig, dat, self.loc, self.default_calling_convention) 1389 }) 1390 } 1391 Some(Token::FuncRef(..)) => { 1392 self.start_gathering_comments(); 1393 self.parse_function_decl(ctx) 1394 .and_then(|(fn_, dat)| ctx.add_fn(fn_, dat, self.loc)) 1395 } 1396 Some(Token::JumpTable(..)) => { 1397 self.start_gathering_comments(); 1398 self.parse_jump_table_decl() 1399 .and_then(|(jt, dat)| ctx.add_jt(jt, dat, self.loc)) 1400 } 1401 Some(Token::Constant(..)) => { 1402 self.start_gathering_comments(); 1403 self.parse_constant_decl() 1404 .and_then(|(c, v)| ctx.add_constant(c, v, self.loc)) 1405 } 1406 Some(Token::Identifier("stack_limit")) => { 1407 self.start_gathering_comments(); 1408 self.parse_stack_limit_decl() 1409 .and_then(|gv| ctx.add_stack_limit(gv, self.loc)) 1410 } 1411 // More to come.. 1412 _ => return Ok(()), 1413 }?; 1414 } 1415 } 1416 1417 // Parse a stack slot decl. 1418 // 1419 // stack-slot-decl ::= * StackSlot(ss) "=" stack-slot-kind Bytes {"," stack-slot-flag} 1420 // stack-slot-kind ::= "explicit_slot" 1421 // | "spill_slot" 1422 // | "incoming_arg" 1423 // | "outgoing_arg" 1424 fn parse_stack_slot_decl(&mut self) -> ParseResult<(StackSlot, StackSlotData)> { 1425 let ss = self.match_ss("expected stack slot number: ss«n»")?; 1426 self.match_token(Token::Equal, "expected '=' in stack slot declaration")?; 1427 let kind = self.match_enum("expected stack slot kind")?; 1428 1429 // stack-slot-decl ::= StackSlot(ss) "=" stack-slot-kind * Bytes {"," stack-slot-flag} 1430 let bytes: i64 = self 1431 .match_imm64("expected byte-size in stack_slot decl")? 1432 .into(); 1433 if bytes < 0 { 1434 return err!(self.loc, "negative stack slot size"); 1435 } 1436 if bytes > i64::from(u32::MAX) { 1437 return err!(self.loc, "stack slot too large"); 1438 } 1439 let data = StackSlotData::new(kind, bytes as u32); 1440 1441 // Collect any trailing comments. 1442 self.token(); 1443 self.claim_gathered_comments(ss); 1444 1445 // TBD: stack-slot-decl ::= StackSlot(ss) "=" stack-slot-kind Bytes * {"," stack-slot-flag} 1446 Ok((ss, data)) 1447 } 1448 1449 // Parse a global value decl. 1450 // 1451 // global-val-decl ::= * GlobalValue(gv) "=" global-val-desc 1452 // global-val-desc ::= "vmctx" 1453 // | "load" "." type "notrap" "aligned" GlobalValue(base) [offset] 1454 // | "iadd_imm" "(" GlobalValue(base) ")" imm64 1455 // | "symbol" ["colocated"] name + imm64 1456 // 1457 fn parse_global_value_decl(&mut self) -> ParseResult<(GlobalValue, GlobalValueData)> { 1458 let gv = self.match_gv("expected global value number: gv«n»")?; 1459 1460 self.match_token(Token::Equal, "expected '=' in global value declaration")?; 1461 1462 let data = match self.match_any_identifier("expected global value kind")? { 1463 "vmctx" => GlobalValueData::VMContext, 1464 "load" => { 1465 self.match_token( 1466 Token::Dot, 1467 "expected '.' followed by type in load global value decl", 1468 )?; 1469 let global_type = self.match_type("expected load type")?; 1470 let flags = self.optional_memflags(); 1471 let base = self.match_gv("expected global value: gv«n»")?; 1472 let offset = self.optional_offset32()?; 1473 1474 if !(flags.notrap() && flags.aligned()) { 1475 return err!(self.loc, "global-value load must be notrap and aligned"); 1476 } 1477 GlobalValueData::Load { 1478 base, 1479 offset, 1480 global_type, 1481 readonly: flags.readonly(), 1482 } 1483 } 1484 "iadd_imm" => { 1485 self.match_token( 1486 Token::Dot, 1487 "expected '.' followed by type in iadd_imm global value decl", 1488 )?; 1489 let global_type = self.match_type("expected iadd type")?; 1490 let base = self.match_gv("expected global value: gv«n»")?; 1491 self.match_token( 1492 Token::Comma, 1493 "expected ',' followed by rhs in iadd_imm global value decl", 1494 )?; 1495 let offset = self.match_imm64("expected iadd_imm immediate")?; 1496 GlobalValueData::IAddImm { 1497 base, 1498 offset, 1499 global_type, 1500 } 1501 } 1502 "symbol" => { 1503 let colocated = self.optional(Token::Identifier("colocated")); 1504 let tls = self.optional(Token::Identifier("tls")); 1505 let name = self.parse_external_name()?; 1506 let offset = self.optional_offset_imm64()?; 1507 GlobalValueData::Symbol { 1508 name, 1509 offset, 1510 colocated, 1511 tls, 1512 } 1513 } 1514 other => return err!(self.loc, "Unknown global value kind '{}'", other), 1515 }; 1516 1517 // Collect any trailing comments. 1518 self.token(); 1519 self.claim_gathered_comments(gv); 1520 1521 Ok((gv, data)) 1522 } 1523 1524 // Parse a heap decl. 1525 // 1526 // heap-decl ::= * Heap(heap) "=" heap-desc 1527 // heap-desc ::= heap-style heap-base { "," heap-attr } 1528 // heap-style ::= "static" | "dynamic" 1529 // heap-base ::= GlobalValue(base) 1530 // heap-attr ::= "min" Imm64(bytes) 1531 // | "bound" Imm64(bytes) 1532 // | "offset_guard" Imm64(bytes) 1533 // | "index_type" type 1534 // 1535 fn parse_heap_decl(&mut self) -> ParseResult<(Heap, HeapData)> { 1536 let heap = self.match_heap("expected heap number: heap«n»")?; 1537 self.match_token(Token::Equal, "expected '=' in heap declaration")?; 1538 1539 let style_name = self.match_any_identifier("expected 'static' or 'dynamic'")?; 1540 1541 // heap-desc ::= heap-style * heap-base { "," heap-attr } 1542 // heap-base ::= * GlobalValue(base) 1543 let base = match self.token() { 1544 Some(Token::GlobalValue(base_num)) => match GlobalValue::with_number(base_num) { 1545 Some(gv) => gv, 1546 None => return err!(self.loc, "invalid global value number for heap base"), 1547 }, 1548 _ => return err!(self.loc, "expected heap base"), 1549 }; 1550 self.consume(); 1551 1552 let mut data = HeapData { 1553 base, 1554 min_size: 0.into(), 1555 offset_guard_size: 0.into(), 1556 style: HeapStyle::Static { bound: 0.into() }, 1557 index_type: ir::types::I32, 1558 }; 1559 1560 // heap-desc ::= heap-style heap-base * { "," heap-attr } 1561 while self.optional(Token::Comma) { 1562 match self.match_any_identifier("expected heap attribute name")? { 1563 "min" => { 1564 data.min_size = self.match_uimm64("expected integer min size")?; 1565 } 1566 "bound" => { 1567 data.style = match style_name { 1568 "dynamic" => HeapStyle::Dynamic { 1569 bound_gv: self.match_gv("expected gv bound")?, 1570 }, 1571 "static" => HeapStyle::Static { 1572 bound: self.match_uimm64("expected integer bound")?, 1573 }, 1574 t => return err!(self.loc, "unknown heap style '{}'", t), 1575 }; 1576 } 1577 "offset_guard" => { 1578 data.offset_guard_size = 1579 self.match_uimm64("expected integer offset-guard size")?; 1580 } 1581 "index_type" => { 1582 data.index_type = self.match_type("expected index type")?; 1583 } 1584 t => return err!(self.loc, "unknown heap attribute '{}'", t), 1585 } 1586 } 1587 1588 // Collect any trailing comments. 1589 self.token(); 1590 self.claim_gathered_comments(heap); 1591 1592 Ok((heap, data)) 1593 } 1594 1595 // Parse a table decl. 1596 // 1597 // table-decl ::= * Table(table) "=" table-desc 1598 // table-desc ::= table-style table-base { "," table-attr } 1599 // table-style ::= "dynamic" 1600 // table-base ::= GlobalValue(base) 1601 // table-attr ::= "min" Imm64(bytes) 1602 // | "bound" Imm64(bytes) 1603 // | "element_size" Imm64(bytes) 1604 // | "index_type" type 1605 // 1606 fn parse_table_decl(&mut self) -> ParseResult<(Table, TableData)> { 1607 let table = self.match_table("expected table number: table«n»")?; 1608 self.match_token(Token::Equal, "expected '=' in table declaration")?; 1609 1610 let style_name = self.match_any_identifier("expected 'static' or 'dynamic'")?; 1611 1612 // table-desc ::= table-style * table-base { "," table-attr } 1613 // table-base ::= * GlobalValue(base) 1614 let base = match self.token() { 1615 Some(Token::GlobalValue(base_num)) => match GlobalValue::with_number(base_num) { 1616 Some(gv) => gv, 1617 None => return err!(self.loc, "invalid global value number for table base"), 1618 }, 1619 _ => return err!(self.loc, "expected table base"), 1620 }; 1621 self.consume(); 1622 1623 let mut data = TableData { 1624 base_gv: base, 1625 min_size: 0.into(), 1626 bound_gv: GlobalValue::reserved_value(), 1627 element_size: 0.into(), 1628 index_type: ir::types::I32, 1629 }; 1630 1631 // table-desc ::= * { "," table-attr } 1632 while self.optional(Token::Comma) { 1633 match self.match_any_identifier("expected table attribute name")? { 1634 "min" => { 1635 data.min_size = self.match_uimm64("expected integer min size")?; 1636 } 1637 "bound" => { 1638 data.bound_gv = match style_name { 1639 "dynamic" => self.match_gv("expected gv bound")?, 1640 t => return err!(self.loc, "unknown table style '{}'", t), 1641 }; 1642 } 1643 "element_size" => { 1644 data.element_size = self.match_uimm64("expected integer element size")?; 1645 } 1646 "index_type" => { 1647 data.index_type = self.match_type("expected index type")?; 1648 } 1649 t => return err!(self.loc, "unknown table attribute '{}'", t), 1650 } 1651 } 1652 1653 // Collect any trailing comments. 1654 self.token(); 1655 self.claim_gathered_comments(table); 1656 1657 Ok((table, data)) 1658 } 1659 1660 // Parse a signature decl. 1661 // 1662 // signature-decl ::= SigRef(sigref) "=" signature 1663 // 1664 fn parse_signature_decl(&mut self) -> ParseResult<(SigRef, Signature)> { 1665 let sig = self.match_sig("expected signature number: sig«n»")?; 1666 self.match_token(Token::Equal, "expected '=' in signature decl")?; 1667 let data = self.parse_signature()?; 1668 1669 // Collect any trailing comments. 1670 self.token(); 1671 self.claim_gathered_comments(sig); 1672 1673 Ok((sig, data)) 1674 } 1675 1676 // Parse a function decl. 1677 // 1678 // Two variants: 1679 // 1680 // function-decl ::= FuncRef(fnref) "=" ["colocated"]" name function-decl-sig 1681 // function-decl-sig ::= SigRef(sig) | signature 1682 // 1683 // The first variant allocates a new signature reference. The second references an existing 1684 // signature which must be declared first. 1685 // 1686 fn parse_function_decl(&mut self, ctx: &mut Context) -> ParseResult<(FuncRef, ExtFuncData)> { 1687 let fn_ = self.match_fn("expected function number: fn«n»")?; 1688 self.match_token(Token::Equal, "expected '=' in function decl")?; 1689 1690 let loc = self.loc; 1691 1692 // function-decl ::= FuncRef(fnref) "=" * ["colocated"] name function-decl-sig 1693 let colocated = self.optional(Token::Identifier("colocated")); 1694 1695 // function-decl ::= FuncRef(fnref) "=" ["colocated"] * name function-decl-sig 1696 let name = self.parse_external_name()?; 1697 1698 // function-decl ::= FuncRef(fnref) "=" ["colocated"] name * function-decl-sig 1699 let data = match self.token() { 1700 Some(Token::LPar) => { 1701 // function-decl ::= FuncRef(fnref) "=" ["colocated"] name * signature 1702 let sig = self.parse_signature()?; 1703 let sigref = ctx.function.import_signature(sig); 1704 ctx.map 1705 .def_entity(sigref.into(), loc) 1706 .expect("duplicate SigRef entities created"); 1707 ExtFuncData { 1708 name, 1709 signature: sigref, 1710 colocated, 1711 } 1712 } 1713 Some(Token::SigRef(sig_src)) => { 1714 let sig = match SigRef::with_number(sig_src) { 1715 None => { 1716 return err!(self.loc, "attempted to use invalid signature ss{}", sig_src); 1717 } 1718 Some(sig) => sig, 1719 }; 1720 ctx.check_sig(sig, self.loc)?; 1721 self.consume(); 1722 ExtFuncData { 1723 name, 1724 signature: sig, 1725 colocated, 1726 } 1727 } 1728 _ => return err!(self.loc, "expected 'function' or sig«n» in function decl"), 1729 }; 1730 1731 // Collect any trailing comments. 1732 self.token(); 1733 self.claim_gathered_comments(fn_); 1734 1735 Ok((fn_, data)) 1736 } 1737 1738 // Parse a jump table decl. 1739 // 1740 // jump-table-decl ::= * JumpTable(jt) "=" "jump_table" "[" jt-entry {"," jt-entry} "]" 1741 fn parse_jump_table_decl(&mut self) -> ParseResult<(JumpTable, JumpTableData)> { 1742 let jt = self.match_jt()?; 1743 self.match_token(Token::Equal, "expected '=' in jump_table decl")?; 1744 self.match_identifier("jump_table", "expected 'jump_table'")?; 1745 self.match_token(Token::LBracket, "expected '[' before jump table contents")?; 1746 1747 let mut data = JumpTableData::new(); 1748 1749 // jump-table-decl ::= JumpTable(jt) "=" "jump_table" "[" * Block(dest) {"," Block(dest)} "]" 1750 match self.token() { 1751 Some(Token::Block(dest)) => { 1752 self.consume(); 1753 data.push_entry(dest); 1754 1755 loop { 1756 match self.token() { 1757 Some(Token::Comma) => { 1758 self.consume(); 1759 if let Some(Token::Block(dest)) = self.token() { 1760 self.consume(); 1761 data.push_entry(dest); 1762 } else { 1763 return err!(self.loc, "expected jump_table entry"); 1764 } 1765 } 1766 Some(Token::RBracket) => break, 1767 _ => return err!(self.loc, "expected ']' after jump table contents"), 1768 } 1769 } 1770 } 1771 Some(Token::RBracket) => (), 1772 _ => return err!(self.loc, "expected jump_table entry"), 1773 } 1774 1775 self.consume(); 1776 1777 // Collect any trailing comments. 1778 self.token(); 1779 self.claim_gathered_comments(jt); 1780 1781 Ok((jt, data)) 1782 } 1783 1784 // Parse a constant decl. 1785 // 1786 // constant-decl ::= * Constant(c) "=" ty? "[" literal {"," literal} "]" 1787 fn parse_constant_decl(&mut self) -> ParseResult<(Constant, ConstantData)> { 1788 let name = self.match_constant()?; 1789 self.match_token(Token::Equal, "expected '=' in constant decl")?; 1790 let data = if let Some(Token::Type(_)) = self.token() { 1791 let ty = self.match_type("expected type of constant")?; 1792 self.match_uimm128(ty) 1793 } else { 1794 self.match_constant_data() 1795 }?; 1796 1797 // Collect any trailing comments. 1798 self.token(); 1799 self.claim_gathered_comments(name); 1800 1801 Ok((name, data)) 1802 } 1803 1804 // Parse a stack limit decl 1805 // 1806 // stack-limit-decl ::= * StackLimit "=" GlobalValue(gv) 1807 fn parse_stack_limit_decl(&mut self) -> ParseResult<GlobalValue> { 1808 self.match_stack_limit()?; 1809 self.match_token(Token::Equal, "expected '=' in stack limit decl")?; 1810 let limit = match self.token() { 1811 Some(Token::GlobalValue(base_num)) => match GlobalValue::with_number(base_num) { 1812 Some(gv) => gv, 1813 None => return err!(self.loc, "invalid global value number for stack limit"), 1814 }, 1815 _ => return err!(self.loc, "expected global value"), 1816 }; 1817 self.consume(); 1818 1819 // Collect any trailing comments. 1820 self.token(); 1821 self.claim_gathered_comments(AnyEntity::StackLimit); 1822 1823 Ok(limit) 1824 } 1825 1826 // Parse a function body, add contents to `ctx`. 1827 // 1828 // function-body ::= * { extended-basic-block } 1829 // 1830 fn parse_function_body(&mut self, ctx: &mut Context) -> ParseResult<()> { 1831 while self.token() != Some(Token::RBrace) { 1832 self.parse_basic_block(ctx)?; 1833 } 1834 1835 // Now that we've seen all defined values in the function, ensure that 1836 // all references refer to a definition. 1837 for block in &ctx.function.layout { 1838 for inst in ctx.function.layout.block_insts(block) { 1839 for value in ctx.function.dfg.inst_args(inst) { 1840 if !ctx.map.contains_value(*value) { 1841 return err!( 1842 ctx.map.location(AnyEntity::Inst(inst)).unwrap(), 1843 "undefined operand value {}", 1844 value 1845 ); 1846 } 1847 } 1848 } 1849 } 1850 1851 for alias in &ctx.aliases { 1852 if !ctx.function.dfg.set_alias_type_for_parser(*alias) { 1853 let loc = ctx.map.location(AnyEntity::Value(*alias)).unwrap(); 1854 return err!(loc, "alias cycle involving {}", alias); 1855 } 1856 } 1857 1858 Ok(()) 1859 } 1860 1861 // Parse a basic block, add contents to `ctx`. 1862 // 1863 // extended-basic-block ::= * block-header { instruction } 1864 // block-header ::= Block(block) [block-params] [block-flags] ":" 1865 // block-flags ::= [Cold] 1866 // 1867 fn parse_basic_block(&mut self, ctx: &mut Context) -> ParseResult<()> { 1868 // Collect comments for the next block. 1869 self.start_gathering_comments(); 1870 1871 let block_num = self.match_block("expected block header")?; 1872 let block = ctx.add_block(block_num, self.loc)?; 1873 1874 if block_num.as_u32() >= MAX_BLOCKS_IN_A_FUNCTION { 1875 return Err(self.error("too many blocks")); 1876 } 1877 1878 if self.token() == Some(Token::LPar) { 1879 self.parse_block_params(ctx, block)?; 1880 } 1881 1882 if self.optional(Token::Cold) { 1883 ctx.set_cold_block(block); 1884 } 1885 1886 self.match_token(Token::Colon, "expected ':' after block parameters")?; 1887 1888 // Collect any trailing comments. 1889 self.token(); 1890 self.claim_gathered_comments(block); 1891 1892 // extended-basic-block ::= block-header * { instruction } 1893 while match self.token() { 1894 Some(Token::Value(_)) 1895 | Some(Token::Identifier(_)) 1896 | Some(Token::LBracket) 1897 | Some(Token::SourceLoc(_)) => true, 1898 _ => false, 1899 } { 1900 let srcloc = self.optional_srcloc()?; 1901 1902 // We need to parse instruction results here because they are shared 1903 // between the parsing of value aliases and the parsing of instructions. 1904 // 1905 // inst-results ::= Value(v) { "," Value(v) } 1906 let results = self.parse_inst_results()?; 1907 1908 for result in &results { 1909 while ctx.function.dfg.num_values() <= result.index() { 1910 ctx.function.dfg.make_invalid_value_for_parser(); 1911 } 1912 } 1913 1914 match self.token() { 1915 Some(Token::Arrow) => { 1916 self.consume(); 1917 self.parse_value_alias(&results, ctx)?; 1918 } 1919 Some(Token::Equal) => { 1920 self.consume(); 1921 self.parse_instruction(&results, srcloc, ctx, block)?; 1922 } 1923 _ if !results.is_empty() => return err!(self.loc, "expected -> or ="), 1924 _ => self.parse_instruction(&results, srcloc, ctx, block)?, 1925 } 1926 } 1927 1928 Ok(()) 1929 } 1930 1931 // Parse parenthesized list of block parameters. Returns a vector of (u32, Type) pairs with the 1932 // value numbers of the defined values and the defined types. 1933 // 1934 // block-params ::= * "(" block-param { "," block-param } ")" 1935 fn parse_block_params(&mut self, ctx: &mut Context, block: Block) -> ParseResult<()> { 1936 // block-params ::= * "(" block-param { "," block-param } ")" 1937 self.match_token(Token::LPar, "expected '(' before block parameters")?; 1938 1939 // block-params ::= "(" * block-param { "," block-param } ")" 1940 self.parse_block_param(ctx, block)?; 1941 1942 // block-params ::= "(" block-param * { "," block-param } ")" 1943 while self.optional(Token::Comma) { 1944 // block-params ::= "(" block-param { "," * block-param } ")" 1945 self.parse_block_param(ctx, block)?; 1946 } 1947 1948 // block-params ::= "(" block-param { "," block-param } * ")" 1949 self.match_token(Token::RPar, "expected ')' after block parameters")?; 1950 1951 Ok(()) 1952 } 1953 1954 // Parse a single block parameter declaration, and append it to `block`. 1955 // 1956 // block-param ::= * Value(v) ":" Type(t) arg-loc? 1957 // arg-loc ::= "[" value-location "]" 1958 // 1959 fn parse_block_param(&mut self, ctx: &mut Context, block: Block) -> ParseResult<()> { 1960 // block-param ::= * Value(v) ":" Type(t) arg-loc? 1961 let v = self.match_value("block argument must be a value")?; 1962 let v_location = self.loc; 1963 // block-param ::= Value(v) * ":" Type(t) arg-loc? 1964 self.match_token(Token::Colon, "expected ':' after block argument")?; 1965 // block-param ::= Value(v) ":" * Type(t) arg-loc? 1966 1967 while ctx.function.dfg.num_values() <= v.index() { 1968 ctx.function.dfg.make_invalid_value_for_parser(); 1969 } 1970 1971 let t = self.match_type("expected block argument type")?; 1972 // Allocate the block argument. 1973 ctx.function.dfg.append_block_param_for_parser(block, t, v); 1974 ctx.map.def_value(v, v_location)?; 1975 1976 Ok(()) 1977 } 1978 1979 // Parse instruction results and return them. 1980 // 1981 // inst-results ::= Value(v) { "," Value(v) } 1982 // 1983 fn parse_inst_results(&mut self) -> ParseResult<SmallVec<[Value; 1]>> { 1984 // Result value numbers. 1985 let mut results = SmallVec::new(); 1986 1987 // instruction ::= * [inst-results "="] Opcode(opc) ["." Type] ... 1988 // inst-results ::= * Value(v) { "," Value(v) } 1989 if let Some(Token::Value(v)) = self.token() { 1990 self.consume(); 1991 1992 results.push(v); 1993 1994 // inst-results ::= Value(v) * { "," Value(v) } 1995 while self.optional(Token::Comma) { 1996 // inst-results ::= Value(v) { "," * Value(v) } 1997 results.push(self.match_value("expected result value")?); 1998 } 1999 } 2000 2001 Ok(results) 2002 } 2003 2004 // Parse a value alias, and append it to `block`. 2005 // 2006 // value_alias ::= [inst-results] "->" Value(v) 2007 // 2008 fn parse_value_alias(&mut self, results: &[Value], ctx: &mut Context) -> ParseResult<()> { 2009 if results.len() != 1 { 2010 return err!(self.loc, "wrong number of aliases"); 2011 } 2012 let result = results[0]; 2013 let dest = self.match_value("expected value alias")?; 2014 2015 // Allow duplicate definitions of aliases, as long as they are identical. 2016 if ctx.map.contains_value(result) { 2017 if let Some(old) = ctx.function.dfg.value_alias_dest_for_serialization(result) { 2018 if old != dest { 2019 return err!( 2020 self.loc, 2021 "value {} is already defined as an alias with destination {}", 2022 result, 2023 old 2024 ); 2025 } 2026 } else { 2027 return err!(self.loc, "value {} is already defined"); 2028 } 2029 } else { 2030 ctx.map.def_value(result, self.loc)?; 2031 } 2032 2033 if !ctx.map.contains_value(dest) { 2034 return err!(self.loc, "value {} is not yet defined", dest); 2035 } 2036 2037 ctx.function 2038 .dfg 2039 .make_value_alias_for_serialization(dest, result); 2040 2041 ctx.aliases.push(result); 2042 Ok(()) 2043 } 2044 2045 // Parse an instruction, append it to `block`. 2046 // 2047 // instruction ::= [inst-results "="] Opcode(opc) ["." Type] ... 2048 // 2049 fn parse_instruction( 2050 &mut self, 2051 results: &[Value], 2052 srcloc: ir::SourceLoc, 2053 ctx: &mut Context, 2054 block: Block, 2055 ) -> ParseResult<()> { 2056 // Define the result values. 2057 for val in results { 2058 ctx.map.def_value(*val, self.loc)?; 2059 } 2060 2061 // Collect comments for the next instruction. 2062 self.start_gathering_comments(); 2063 2064 // instruction ::= [inst-results "="] * Opcode(opc) ["." Type] ... 2065 let opcode = if let Some(Token::Identifier(text)) = self.token() { 2066 match text.parse() { 2067 Ok(opc) => opc, 2068 Err(msg) => return err!(self.loc, "{}: '{}'", msg, text), 2069 } 2070 } else { 2071 return err!(self.loc, "expected instruction opcode"); 2072 }; 2073 let opcode_loc = self.loc; 2074 self.consume(); 2075 2076 // Look for a controlling type variable annotation. 2077 // instruction ::= [inst-results "="] Opcode(opc) * ["." Type] ... 2078 let explicit_ctrl_type = if self.optional(Token::Dot) { 2079 Some(self.match_type("expected type after 'opcode.'")?) 2080 } else { 2081 None 2082 }; 2083 2084 // instruction ::= [inst-results "="] Opcode(opc) ["." Type] * ... 2085 let inst_data = self.parse_inst_operands(ctx, opcode, explicit_ctrl_type)?; 2086 2087 // We're done parsing the instruction now. 2088 // 2089 // We still need to check that the number of result values in the source matches the opcode 2090 // or function call signature. We also need to create values with the right type for all 2091 // the instruction results. 2092 let ctrl_typevar = self.infer_typevar(ctx, opcode, explicit_ctrl_type, &inst_data)?; 2093 let inst = ctx.function.dfg.make_inst(inst_data); 2094 let num_results = 2095 ctx.function 2096 .dfg 2097 .make_inst_results_for_parser(inst, ctrl_typevar, results); 2098 ctx.function.layout.append_inst(inst, block); 2099 ctx.map 2100 .def_entity(inst.into(), opcode_loc) 2101 .expect("duplicate inst references created"); 2102 2103 if !srcloc.is_default() { 2104 ctx.function.srclocs[inst] = srcloc; 2105 } 2106 2107 if results.len() != num_results { 2108 return err!( 2109 self.loc, 2110 "instruction produces {} result values, {} given", 2111 num_results, 2112 results.len() 2113 ); 2114 } 2115 2116 // Collect any trailing comments. 2117 self.token(); 2118 self.claim_gathered_comments(inst); 2119 2120 Ok(()) 2121 } 2122 2123 // Type inference for polymorphic instructions. 2124 // 2125 // The controlling type variable can be specified explicitly as 'splat.i32x4 v5', or it can be 2126 // inferred from `inst_data.typevar_operand` for some opcodes. 2127 // 2128 // Returns the controlling typevar for a polymorphic opcode, or `INVALID` for a non-polymorphic 2129 // opcode. 2130 fn infer_typevar( 2131 &self, 2132 ctx: &Context, 2133 opcode: Opcode, 2134 explicit_ctrl_type: Option<Type>, 2135 inst_data: &InstructionData, 2136 ) -> ParseResult<Type> { 2137 let constraints = opcode.constraints(); 2138 let ctrl_type = match explicit_ctrl_type { 2139 Some(t) => t, 2140 None => { 2141 if constraints.use_typevar_operand() { 2142 // This is an opcode that supports type inference, AND there was no 2143 // explicit type specified. Look up `ctrl_value` to see if it was defined 2144 // already. 2145 // TBD: If it is defined in another block, the type should have been 2146 // specified explicitly. It is unfortunate that the correctness of IR 2147 // depends on the layout of the blocks. 2148 let ctrl_src_value = inst_data 2149 .typevar_operand(&ctx.function.dfg.value_lists) 2150 .expect("Constraints <-> Format inconsistency"); 2151 if !ctx.map.contains_value(ctrl_src_value) { 2152 return err!( 2153 self.loc, 2154 "type variable required for polymorphic opcode, e.g. '{}.{}'; \ 2155 can't infer from {} which is not yet defined", 2156 opcode, 2157 constraints.ctrl_typeset().unwrap().example(), 2158 ctrl_src_value 2159 ); 2160 } 2161 if !ctx.function.dfg.value_is_valid_for_parser(ctrl_src_value) { 2162 return err!( 2163 self.loc, 2164 "type variable required for polymorphic opcode, e.g. '{}.{}'; \ 2165 can't infer from {} which is not yet resolved", 2166 opcode, 2167 constraints.ctrl_typeset().unwrap().example(), 2168 ctrl_src_value 2169 ); 2170 } 2171 ctx.function.dfg.value_type(ctrl_src_value) 2172 } else if constraints.is_polymorphic() { 2173 // This opcode does not support type inference, so the explicit type 2174 // variable is required. 2175 return err!( 2176 self.loc, 2177 "type variable required for polymorphic opcode, e.g. '{}.{}'", 2178 opcode, 2179 constraints.ctrl_typeset().unwrap().example() 2180 ); 2181 } else { 2182 // This is a non-polymorphic opcode. No typevar needed. 2183 INVALID 2184 } 2185 } 2186 }; 2187 2188 // Verify that `ctrl_type` is valid for the controlling type variable. We don't want to 2189 // attempt deriving types from an incorrect basis. 2190 // This is not a complete type check. The verifier does that. 2191 if let Some(typeset) = constraints.ctrl_typeset() { 2192 // This is a polymorphic opcode. 2193 if !typeset.contains(ctrl_type) { 2194 return err!( 2195 self.loc, 2196 "{} is not a valid typevar for {}", 2197 ctrl_type, 2198 opcode 2199 ); 2200 } 2201 // Treat it as a syntax error to specify a typevar on a non-polymorphic opcode. 2202 } else if ctrl_type != INVALID { 2203 return err!(self.loc, "{} does not take a typevar", opcode); 2204 } 2205 2206 Ok(ctrl_type) 2207 } 2208 2209 // Parse comma-separated value list into a VariableArgs struct. 2210 // 2211 // value_list ::= [ value { "," value } ] 2212 // 2213 fn parse_value_list(&mut self) -> ParseResult<VariableArgs> { 2214 let mut args = VariableArgs::new(); 2215 2216 if let Some(Token::Value(v)) = self.token() { 2217 args.push(v); 2218 self.consume(); 2219 } else { 2220 return Ok(args); 2221 } 2222 2223 while self.optional(Token::Comma) { 2224 args.push(self.match_value("expected value in argument list")?); 2225 } 2226 2227 Ok(args) 2228 } 2229 2230 fn parse_value_sequence(&mut self) -> ParseResult<VariableArgs> { 2231 let mut args = VariableArgs::new(); 2232 2233 if let Some(Token::Value(v)) = self.token() { 2234 args.push(v); 2235 self.consume(); 2236 } else { 2237 return Ok(args); 2238 } 2239 2240 while self.optional(Token::Plus) { 2241 args.push(self.match_value("expected value in argument list")?); 2242 } 2243 2244 Ok(args) 2245 } 2246 2247 // Parse an optional value list enclosed in parentheses. 2248 fn parse_opt_value_list(&mut self) -> ParseResult<VariableArgs> { 2249 if !self.optional(Token::LPar) { 2250 return Ok(VariableArgs::new()); 2251 } 2252 2253 let args = self.parse_value_list()?; 2254 2255 self.match_token(Token::RPar, "expected ')' after arguments")?; 2256 2257 Ok(args) 2258 } 2259 2260 /// Parse a vmctx offset annotation 2261 /// 2262 /// vmctx-offset ::= "vmctx" "+" UImm64(offset) 2263 fn parse_vmctx_offset(&mut self) -> ParseResult<Uimm64> { 2264 self.match_token(Token::Identifier("vmctx"), "expected a 'vmctx' token")?; 2265 2266 // The '+' token here gets parsed as part of the integer text, so we can't just match_token it 2267 // and `match_uimm64` doesn't support leading '+' tokens, so we can't use that either. 2268 match self.token() { 2269 Some(Token::Integer(text)) if text.starts_with('+') => { 2270 self.consume(); 2271 2272 text[1..] 2273 .parse() 2274 .map_err(|_| self.error("expected u64 decimal immediate")) 2275 } 2276 token => err!( 2277 self.loc, 2278 format!("Unexpected token {:?} after vmctx", token) 2279 ), 2280 } 2281 } 2282 2283 /// Parse a CLIF heap command. 2284 /// 2285 /// heap-command ::= "heap" ":" heap-type { "," heap-attr } 2286 /// heap-attr ::= "size" "=" UImm64(bytes) 2287 fn parse_heap_command(&mut self) -> ParseResult<HeapCommand> { 2288 self.match_token(Token::Identifier("heap"), "expected a 'heap:' command")?; 2289 self.match_token(Token::Colon, "expected a ':' after heap command")?; 2290 2291 let mut heap_command = HeapCommand { 2292 heap_type: self.parse_heap_type()?, 2293 size: Uimm64::new(0), 2294 ptr_offset: None, 2295 bound_offset: None, 2296 }; 2297 2298 while self.optional(Token::Comma) { 2299 let identifier = self.match_any_identifier("expected heap attribute name")?; 2300 self.match_token(Token::Equal, "expected '=' after heap attribute name")?; 2301 2302 match identifier { 2303 "size" => { 2304 heap_command.size = self.match_uimm64("expected integer size")?; 2305 } 2306 "ptr" => { 2307 heap_command.ptr_offset = Some(self.parse_vmctx_offset()?); 2308 } 2309 "bound" => { 2310 heap_command.bound_offset = Some(self.parse_vmctx_offset()?); 2311 } 2312 t => return err!(self.loc, "unknown heap attribute '{}'", t), 2313 } 2314 } 2315 2316 if heap_command.size == Uimm64::new(0) { 2317 return err!(self.loc, self.error("Expected a heap size to be specified")); 2318 } 2319 2320 Ok(heap_command) 2321 } 2322 2323 /// Parse a heap type. 2324 /// 2325 /// heap-type ::= "static" | "dynamic" 2326 fn parse_heap_type(&mut self) -> ParseResult<HeapType> { 2327 match self.token() { 2328 Some(Token::Identifier("static")) => { 2329 self.consume(); 2330 Ok(HeapType::Static) 2331 } 2332 Some(Token::Identifier("dynamic")) => { 2333 self.consume(); 2334 Ok(HeapType::Dynamic) 2335 } 2336 _ => Err(self.error("expected a heap type, e.g. static or dynamic")), 2337 } 2338 } 2339 2340 /// Parse a CLIF run command. 2341 /// 2342 /// run-command ::= "run" [":" invocation comparison expected] 2343 /// \ "print" [":" invocation] 2344 fn parse_run_command(&mut self, sig: &Signature) -> ParseResult<RunCommand> { 2345 // skip semicolon 2346 match self.token() { 2347 Some(Token::Identifier("run")) => { 2348 self.consume(); 2349 if self.optional(Token::Colon) { 2350 let invocation = self.parse_run_invocation(sig)?; 2351 let comparison = self.parse_run_comparison()?; 2352 let expected = self.parse_run_returns(sig)?; 2353 Ok(RunCommand::Run(invocation, comparison, expected)) 2354 } else if sig.params.is_empty() 2355 && sig.returns.len() == 1 2356 && sig.returns[0].value_type.is_bool() 2357 { 2358 // To match the existing run behavior that does not require an explicit 2359 // invocation, we create an invocation from a function like `() -> b*` and 2360 // compare it to `true`. 2361 let invocation = Invocation::new("default", vec![]); 2362 let expected = vec![DataValue::B(true)]; 2363 let comparison = Comparison::Equals; 2364 Ok(RunCommand::Run(invocation, comparison, expected)) 2365 } else { 2366 Err(self.error("unable to parse the run command")) 2367 } 2368 } 2369 Some(Token::Identifier("print")) => { 2370 self.consume(); 2371 if self.optional(Token::Colon) { 2372 Ok(RunCommand::Print(self.parse_run_invocation(sig)?)) 2373 } else if sig.params.is_empty() { 2374 // To allow printing of functions like `() -> *`, we create a no-arg invocation. 2375 let invocation = Invocation::new("default", vec![]); 2376 Ok(RunCommand::Print(invocation)) 2377 } else { 2378 Err(self.error("unable to parse the print command")) 2379 } 2380 } 2381 _ => Err(self.error("expected a 'run:' or 'print:' command")), 2382 } 2383 } 2384 2385 /// Parse the invocation of a CLIF function. 2386 /// 2387 /// This is different from parsing a CLIF `call`; it is used in parsing run commands like 2388 /// `run: %fn(42, 4.2) == false`. 2389 /// 2390 /// invocation ::= name "(" [data-value-list] ")" 2391 fn parse_run_invocation(&mut self, sig: &Signature) -> ParseResult<Invocation> { 2392 if let Some(Token::Name(name)) = self.token() { 2393 self.consume(); 2394 self.match_token( 2395 Token::LPar, 2396 "expected invocation parentheses, e.g. %fn(...)", 2397 )?; 2398 2399 let arg_types = sig 2400 .params 2401 .iter() 2402 .enumerate() 2403 .filter_map(|(i, p)| { 2404 // The first argument being VMCtx indicates that this is a argument that is going 2405 // to be passed in with info about the test environment, and should not be passed 2406 // in the run params. 2407 if p.purpose == ir::ArgumentPurpose::VMContext && i == 0 { 2408 None 2409 } else { 2410 Some(p.value_type) 2411 } 2412 }) 2413 .collect::<Vec<_>>(); 2414 let args = self.parse_data_value_list(&arg_types)?; 2415 2416 self.match_token( 2417 Token::RPar, 2418 "expected invocation parentheses, e.g. %fn(...)", 2419 )?; 2420 Ok(Invocation::new(name, args)) 2421 } else { 2422 Err(self.error("expected a function name, e.g. %my_fn")) 2423 } 2424 } 2425 2426 /// Parse a comparison operator for run commands. 2427 /// 2428 /// comparison ::= "==" | "!=" 2429 fn parse_run_comparison(&mut self) -> ParseResult<Comparison> { 2430 if self.optional(Token::Equal) { 2431 self.match_token(Token::Equal, "expected another =")?; 2432 Ok(Comparison::Equals) 2433 } else if self.optional(Token::Not) { 2434 self.match_token(Token::Equal, "expected a =")?; 2435 Ok(Comparison::NotEquals) 2436 } else { 2437 Err(self.error("unable to parse a valid comparison operator")) 2438 } 2439 } 2440 2441 /// Parse the expected return values of a run invocation. 2442 /// 2443 /// expected ::= "[" "]" 2444 /// | data-value 2445 /// | "[" data-value-list "]" 2446 fn parse_run_returns(&mut self, sig: &Signature) -> ParseResult<Vec<DataValue>> { 2447 if sig.returns.len() != 1 { 2448 self.match_token(Token::LBracket, "expected a left bracket [")?; 2449 } 2450 2451 let returns = self 2452 .parse_data_value_list(&sig.returns.iter().map(|a| a.value_type).collect::<Vec<_>>())?; 2453 2454 if sig.returns.len() != 1 { 2455 self.match_token(Token::RBracket, "expected a right bracket ]")?; 2456 } 2457 Ok(returns) 2458 } 2459 2460 /// Parse a comma-separated list of data values. 2461 /// 2462 /// data-value-list ::= [data-value {"," data-value-list}] 2463 fn parse_data_value_list(&mut self, types: &[Type]) -> ParseResult<Vec<DataValue>> { 2464 let mut values = vec![]; 2465 for ty in types.iter().take(1) { 2466 values.push(self.parse_data_value(*ty)?); 2467 } 2468 for ty in types.iter().skip(1) { 2469 self.match_token( 2470 Token::Comma, 2471 "expected a comma between invocation arguments", 2472 )?; 2473 values.push(self.parse_data_value(*ty)?); 2474 } 2475 Ok(values) 2476 } 2477 2478 /// Parse a data value; e.g. `42`, `4.2`, `true`. 2479 /// 2480 /// data-value-list ::= [data-value {"," data-value-list}] 2481 fn parse_data_value(&mut self, ty: Type) -> ParseResult<DataValue> { 2482 let dv = match ty { 2483 I8 => DataValue::from(self.match_imm8("expected a i8")?), 2484 I16 => DataValue::from(self.match_imm16("expected an i16")?), 2485 I32 => DataValue::from(self.match_imm32("expected an i32")?), 2486 I64 => DataValue::from(Into::<i64>::into(self.match_imm64("expected an i64")?)), 2487 I128 => DataValue::from(self.match_imm128("expected an i128")?), 2488 F32 => DataValue::from(self.match_ieee32("expected an f32")?), 2489 F64 => DataValue::from(self.match_ieee64("expected an f64")?), 2490 _ if ty.is_vector() => { 2491 let as_vec = self.match_uimm128(ty)?.into_vec(); 2492 if as_vec.len() == 16 { 2493 let mut as_array = [0; 16]; 2494 as_array.copy_from_slice(&as_vec[..16]); 2495 DataValue::from(as_array) 2496 } else { 2497 return Err(self.error("only 128-bit vectors are currently supported")); 2498 } 2499 } 2500 _ if ty.is_bool() && !ty.is_vector() => { 2501 DataValue::from(self.match_bool("expected a boolean")?) 2502 } 2503 _ => return Err(self.error(&format!("don't know how to parse data values of: {}", ty))), 2504 }; 2505 Ok(dv) 2506 } 2507 2508 // Parse the operands following the instruction opcode. 2509 // This depends on the format of the opcode. 2510 fn parse_inst_operands( 2511 &mut self, 2512 ctx: &mut Context, 2513 opcode: Opcode, 2514 explicit_control_type: Option<Type>, 2515 ) -> ParseResult<InstructionData> { 2516 let idata = match opcode.format() { 2517 InstructionFormat::Unary => InstructionData::Unary { 2518 opcode, 2519 arg: self.match_value("expected SSA value operand")?, 2520 }, 2521 InstructionFormat::UnaryImm => InstructionData::UnaryImm { 2522 opcode, 2523 imm: self.match_imm64("expected immediate integer operand")?, 2524 }, 2525 InstructionFormat::UnaryIeee32 => InstructionData::UnaryIeee32 { 2526 opcode, 2527 imm: self.match_ieee32("expected immediate 32-bit float operand")?, 2528 }, 2529 InstructionFormat::UnaryIeee64 => InstructionData::UnaryIeee64 { 2530 opcode, 2531 imm: self.match_ieee64("expected immediate 64-bit float operand")?, 2532 }, 2533 InstructionFormat::UnaryBool => InstructionData::UnaryBool { 2534 opcode, 2535 imm: self.match_bool("expected immediate boolean operand")?, 2536 }, 2537 InstructionFormat::UnaryConst => { 2538 let constant_handle = if let Some(Token::Constant(_)) = self.token() { 2539 // If handed a `const?`, use that. 2540 let c = self.match_constant()?; 2541 ctx.check_constant(c, self.loc)?; 2542 c 2543 } else if let Some(controlling_type) = explicit_control_type { 2544 // If an explicit control type is present, we expect a sized value and insert 2545 // it in the constant pool. 2546 let uimm128 = self.match_uimm128(controlling_type)?; 2547 ctx.function.dfg.constants.insert(uimm128) 2548 } else { 2549 return err!( 2550 self.loc, 2551 "Expected either a const entity or a typed value, e.g. inst.i32x4 [...]" 2552 ); 2553 }; 2554 InstructionData::UnaryConst { 2555 opcode, 2556 constant_handle, 2557 } 2558 } 2559 InstructionFormat::UnaryGlobalValue => { 2560 let gv = self.match_gv("expected global value")?; 2561 ctx.check_gv(gv, self.loc)?; 2562 InstructionData::UnaryGlobalValue { 2563 opcode, 2564 global_value: gv, 2565 } 2566 } 2567 InstructionFormat::Binary => { 2568 let lhs = self.match_value("expected SSA value first operand")?; 2569 self.match_token(Token::Comma, "expected ',' between operands")?; 2570 let rhs = self.match_value("expected SSA value second operand")?; 2571 InstructionData::Binary { 2572 opcode, 2573 args: [lhs, rhs], 2574 } 2575 } 2576 InstructionFormat::BinaryImm8 => { 2577 let arg = self.match_value("expected SSA value first operand")?; 2578 self.match_token(Token::Comma, "expected ',' between operands")?; 2579 let imm = self.match_uimm8("expected unsigned 8-bit immediate")?; 2580 InstructionData::BinaryImm8 { opcode, arg, imm } 2581 } 2582 InstructionFormat::BinaryImm64 => { 2583 let lhs = self.match_value("expected SSA value first operand")?; 2584 self.match_token(Token::Comma, "expected ',' between operands")?; 2585 let rhs = self.match_imm64("expected immediate integer second operand")?; 2586 InstructionData::BinaryImm64 { 2587 opcode, 2588 arg: lhs, 2589 imm: rhs, 2590 } 2591 } 2592 InstructionFormat::Ternary => { 2593 // Names here refer to the `select` instruction. 2594 // This format is also use by `fma`. 2595 let ctrl_arg = self.match_value("expected SSA value control operand")?; 2596 self.match_token(Token::Comma, "expected ',' between operands")?; 2597 let true_arg = self.match_value("expected SSA value true operand")?; 2598 self.match_token(Token::Comma, "expected ',' between operands")?; 2599 let false_arg = self.match_value("expected SSA value false operand")?; 2600 InstructionData::Ternary { 2601 opcode, 2602 args: [ctrl_arg, true_arg, false_arg], 2603 } 2604 } 2605 InstructionFormat::MultiAry => { 2606 let args = self.parse_value_list()?; 2607 InstructionData::MultiAry { 2608 opcode, 2609 args: args.into_value_list(&[], &mut ctx.function.dfg.value_lists), 2610 } 2611 } 2612 InstructionFormat::NullAry => InstructionData::NullAry { opcode }, 2613 InstructionFormat::Jump => { 2614 // Parse the destination block number. 2615 let block_num = self.match_block("expected jump destination block")?; 2616 let args = self.parse_opt_value_list()?; 2617 InstructionData::Jump { 2618 opcode, 2619 destination: block_num, 2620 args: args.into_value_list(&[], &mut ctx.function.dfg.value_lists), 2621 } 2622 } 2623 InstructionFormat::Branch => { 2624 let ctrl_arg = self.match_value("expected SSA value control operand")?; 2625 self.match_token(Token::Comma, "expected ',' between operands")?; 2626 let block_num = self.match_block("expected branch destination block")?; 2627 let args = self.parse_opt_value_list()?; 2628 InstructionData::Branch { 2629 opcode, 2630 destination: block_num, 2631 args: args.into_value_list(&[ctrl_arg], &mut ctx.function.dfg.value_lists), 2632 } 2633 } 2634 InstructionFormat::BranchInt => { 2635 let cond = self.match_enum("expected intcc condition code")?; 2636 let arg = self.match_value("expected SSA value first operand")?; 2637 self.match_token(Token::Comma, "expected ',' between operands")?; 2638 let block_num = self.match_block("expected branch destination block")?; 2639 let args = self.parse_opt_value_list()?; 2640 InstructionData::BranchInt { 2641 opcode, 2642 cond, 2643 destination: block_num, 2644 args: args.into_value_list(&[arg], &mut ctx.function.dfg.value_lists), 2645 } 2646 } 2647 InstructionFormat::BranchFloat => { 2648 let cond = self.match_enum("expected floatcc condition code")?; 2649 let arg = self.match_value("expected SSA value first operand")?; 2650 self.match_token(Token::Comma, "expected ',' between operands")?; 2651 let block_num = self.match_block("expected branch destination block")?; 2652 let args = self.parse_opt_value_list()?; 2653 InstructionData::BranchFloat { 2654 opcode, 2655 cond, 2656 destination: block_num, 2657 args: args.into_value_list(&[arg], &mut ctx.function.dfg.value_lists), 2658 } 2659 } 2660 InstructionFormat::BranchIcmp => { 2661 let cond = self.match_enum("expected intcc condition code")?; 2662 let lhs = self.match_value("expected SSA value first operand")?; 2663 self.match_token(Token::Comma, "expected ',' between operands")?; 2664 let rhs = self.match_value("expected SSA value second operand")?; 2665 self.match_token(Token::Comma, "expected ',' between operands")?; 2666 let block_num = self.match_block("expected branch destination block")?; 2667 let args = self.parse_opt_value_list()?; 2668 InstructionData::BranchIcmp { 2669 opcode, 2670 cond, 2671 destination: block_num, 2672 args: args.into_value_list(&[lhs, rhs], &mut ctx.function.dfg.value_lists), 2673 } 2674 } 2675 InstructionFormat::BranchTable => { 2676 let arg = self.match_value("expected SSA value operand")?; 2677 self.match_token(Token::Comma, "expected ',' between operands")?; 2678 let block_num = self.match_block("expected branch destination block")?; 2679 self.match_token(Token::Comma, "expected ',' between operands")?; 2680 let table = self.match_jt()?; 2681 ctx.check_jt(table, self.loc)?; 2682 InstructionData::BranchTable { 2683 opcode, 2684 arg, 2685 destination: block_num, 2686 table, 2687 } 2688 } 2689 InstructionFormat::TernaryImm8 => { 2690 let lhs = self.match_value("expected SSA value first operand")?; 2691 self.match_token(Token::Comma, "expected ',' between operands")?; 2692 let rhs = self.match_value("expected SSA value last operand")?; 2693 self.match_token(Token::Comma, "expected ',' between operands")?; 2694 let imm = self.match_uimm8("expected 8-bit immediate")?; 2695 InstructionData::TernaryImm8 { 2696 opcode, 2697 imm, 2698 args: [lhs, rhs], 2699 } 2700 } 2701 InstructionFormat::Shuffle => { 2702 let a = self.match_value("expected SSA value first operand")?; 2703 self.match_token(Token::Comma, "expected ',' between operands")?; 2704 let b = self.match_value("expected SSA value second operand")?; 2705 self.match_token(Token::Comma, "expected ',' between operands")?; 2706 let uimm128 = self.match_uimm128(I8X16)?; 2707 let imm = ctx.function.dfg.immediates.push(uimm128); 2708 InstructionData::Shuffle { 2709 opcode, 2710 imm, 2711 args: [a, b], 2712 } 2713 } 2714 InstructionFormat::IntCompare => { 2715 let cond = self.match_enum("expected intcc condition code")?; 2716 let lhs = self.match_value("expected SSA value first operand")?; 2717 self.match_token(Token::Comma, "expected ',' between operands")?; 2718 let rhs = self.match_value("expected SSA value second operand")?; 2719 InstructionData::IntCompare { 2720 opcode, 2721 cond, 2722 args: [lhs, rhs], 2723 } 2724 } 2725 InstructionFormat::IntCompareImm => { 2726 let cond = self.match_enum("expected intcc condition code")?; 2727 let lhs = self.match_value("expected SSA value first operand")?; 2728 self.match_token(Token::Comma, "expected ',' between operands")?; 2729 let rhs = self.match_imm64("expected immediate second operand")?; 2730 InstructionData::IntCompareImm { 2731 opcode, 2732 cond, 2733 arg: lhs, 2734 imm: rhs, 2735 } 2736 } 2737 InstructionFormat::IntCond => { 2738 let cond = self.match_enum("expected intcc condition code")?; 2739 let arg = self.match_value("expected SSA value")?; 2740 InstructionData::IntCond { opcode, cond, arg } 2741 } 2742 InstructionFormat::FloatCompare => { 2743 let cond = self.match_enum("expected floatcc condition code")?; 2744 let lhs = self.match_value("expected SSA value first operand")?; 2745 self.match_token(Token::Comma, "expected ',' between operands")?; 2746 let rhs = self.match_value("expected SSA value second operand")?; 2747 InstructionData::FloatCompare { 2748 opcode, 2749 cond, 2750 args: [lhs, rhs], 2751 } 2752 } 2753 InstructionFormat::FloatCond => { 2754 let cond = self.match_enum("expected floatcc condition code")?; 2755 let arg = self.match_value("expected SSA value")?; 2756 InstructionData::FloatCond { opcode, cond, arg } 2757 } 2758 InstructionFormat::IntSelect => { 2759 let cond = self.match_enum("expected intcc condition code")?; 2760 let guard = self.match_value("expected SSA value first operand")?; 2761 self.match_token(Token::Comma, "expected ',' between operands")?; 2762 let v_true = self.match_value("expected SSA value second operand")?; 2763 self.match_token(Token::Comma, "expected ',' between operands")?; 2764 let v_false = self.match_value("expected SSA value third operand")?; 2765 InstructionData::IntSelect { 2766 opcode, 2767 cond, 2768 args: [guard, v_true, v_false], 2769 } 2770 } 2771 InstructionFormat::Call => { 2772 let func_ref = self.match_fn("expected function reference")?; 2773 ctx.check_fn(func_ref, self.loc)?; 2774 self.match_token(Token::LPar, "expected '(' before arguments")?; 2775 let args = self.parse_value_list()?; 2776 self.match_token(Token::RPar, "expected ')' after arguments")?; 2777 InstructionData::Call { 2778 opcode, 2779 func_ref, 2780 args: args.into_value_list(&[], &mut ctx.function.dfg.value_lists), 2781 } 2782 } 2783 InstructionFormat::CallIndirect => { 2784 let sig_ref = self.match_sig("expected signature reference")?; 2785 ctx.check_sig(sig_ref, self.loc)?; 2786 self.match_token(Token::Comma, "expected ',' between operands")?; 2787 let callee = self.match_value("expected SSA value callee operand")?; 2788 self.match_token(Token::LPar, "expected '(' before arguments")?; 2789 let args = self.parse_value_list()?; 2790 self.match_token(Token::RPar, "expected ')' after arguments")?; 2791 InstructionData::CallIndirect { 2792 opcode, 2793 sig_ref, 2794 args: args.into_value_list(&[callee], &mut ctx.function.dfg.value_lists), 2795 } 2796 } 2797 InstructionFormat::FuncAddr => { 2798 let func_ref = self.match_fn("expected function reference")?; 2799 ctx.check_fn(func_ref, self.loc)?; 2800 InstructionData::FuncAddr { opcode, func_ref } 2801 } 2802 InstructionFormat::StackLoad => { 2803 let ss = self.match_ss("expected stack slot number: ss«n»")?; 2804 ctx.check_ss(ss, self.loc)?; 2805 let offset = self.optional_offset32()?; 2806 InstructionData::StackLoad { 2807 opcode, 2808 stack_slot: ss, 2809 offset, 2810 } 2811 } 2812 InstructionFormat::StackStore => { 2813 let arg = self.match_value("expected SSA value operand")?; 2814 self.match_token(Token::Comma, "expected ',' between operands")?; 2815 let ss = self.match_ss("expected stack slot number: ss«n»")?; 2816 ctx.check_ss(ss, self.loc)?; 2817 let offset = self.optional_offset32()?; 2818 InstructionData::StackStore { 2819 opcode, 2820 arg, 2821 stack_slot: ss, 2822 offset, 2823 } 2824 } 2825 InstructionFormat::HeapAddr => { 2826 let heap = self.match_heap("expected heap identifier")?; 2827 ctx.check_heap(heap, self.loc)?; 2828 self.match_token(Token::Comma, "expected ',' between operands")?; 2829 let arg = self.match_value("expected SSA value heap address")?; 2830 self.match_token(Token::Comma, "expected ',' between operands")?; 2831 let imm = self.match_uimm32("expected 32-bit integer size")?; 2832 InstructionData::HeapAddr { 2833 opcode, 2834 heap, 2835 arg, 2836 imm, 2837 } 2838 } 2839 InstructionFormat::TableAddr => { 2840 let table = self.match_table("expected table identifier")?; 2841 ctx.check_table(table, self.loc)?; 2842 self.match_token(Token::Comma, "expected ',' between operands")?; 2843 let arg = self.match_value("expected SSA value table address")?; 2844 self.match_token(Token::Comma, "expected ',' between operands")?; 2845 let offset = self.optional_offset32()?; 2846 InstructionData::TableAddr { 2847 opcode, 2848 table, 2849 arg, 2850 offset, 2851 } 2852 } 2853 InstructionFormat::Load => { 2854 let flags = self.optional_memflags(); 2855 let addr = self.match_value("expected SSA value address")?; 2856 let offset = self.optional_offset32()?; 2857 InstructionData::Load { 2858 opcode, 2859 flags, 2860 arg: addr, 2861 offset, 2862 } 2863 } 2864 InstructionFormat::LoadComplex => { 2865 let flags = self.optional_memflags(); 2866 let args = self.parse_value_sequence()?; 2867 let offset = self.optional_offset32()?; 2868 InstructionData::LoadComplex { 2869 opcode, 2870 flags, 2871 args: args.into_value_list(&[], &mut ctx.function.dfg.value_lists), 2872 offset, 2873 } 2874 } 2875 InstructionFormat::Store => { 2876 let flags = self.optional_memflags(); 2877 let arg = self.match_value("expected SSA value operand")?; 2878 self.match_token(Token::Comma, "expected ',' between operands")?; 2879 let addr = self.match_value("expected SSA value address")?; 2880 let offset = self.optional_offset32()?; 2881 InstructionData::Store { 2882 opcode, 2883 flags, 2884 args: [arg, addr], 2885 offset, 2886 } 2887 } 2888 2889 InstructionFormat::StoreComplex => { 2890 let flags = self.optional_memflags(); 2891 let src = self.match_value("expected SSA value operand")?; 2892 self.match_token(Token::Comma, "expected ',' between operands")?; 2893 let args = self.parse_value_sequence()?; 2894 let offset = self.optional_offset32()?; 2895 InstructionData::StoreComplex { 2896 opcode, 2897 flags, 2898 args: args.into_value_list(&[src], &mut ctx.function.dfg.value_lists), 2899 offset, 2900 } 2901 } 2902 InstructionFormat::Trap => { 2903 let code = self.match_enum("expected trap code")?; 2904 InstructionData::Trap { opcode, code } 2905 } 2906 InstructionFormat::CondTrap => { 2907 let arg = self.match_value("expected SSA value operand")?; 2908 self.match_token(Token::Comma, "expected ',' between operands")?; 2909 let code = self.match_enum("expected trap code")?; 2910 InstructionData::CondTrap { opcode, arg, code } 2911 } 2912 InstructionFormat::IntCondTrap => { 2913 let cond = self.match_enum("expected intcc condition code")?; 2914 let arg = self.match_value("expected SSA value operand")?; 2915 self.match_token(Token::Comma, "expected ',' between operands")?; 2916 let code = self.match_enum("expected trap code")?; 2917 InstructionData::IntCondTrap { 2918 opcode, 2919 cond, 2920 arg, 2921 code, 2922 } 2923 } 2924 InstructionFormat::FloatCondTrap => { 2925 let cond = self.match_enum("expected floatcc condition code")?; 2926 let arg = self.match_value("expected SSA value operand")?; 2927 self.match_token(Token::Comma, "expected ',' between operands")?; 2928 let code = self.match_enum("expected trap code")?; 2929 InstructionData::FloatCondTrap { 2930 opcode, 2931 cond, 2932 arg, 2933 code, 2934 } 2935 } 2936 InstructionFormat::AtomicCas => { 2937 let flags = self.optional_memflags(); 2938 let addr = self.match_value("expected SSA value address")?; 2939 self.match_token(Token::Comma, "expected ',' between operands")?; 2940 let expected = self.match_value("expected SSA value address")?; 2941 self.match_token(Token::Comma, "expected ',' between operands")?; 2942 let replacement = self.match_value("expected SSA value address")?; 2943 InstructionData::AtomicCas { 2944 opcode, 2945 flags, 2946 args: [addr, expected, replacement], 2947 } 2948 } 2949 InstructionFormat::AtomicRmw => { 2950 let flags = self.optional_memflags(); 2951 let op = self.match_enum("expected AtomicRmwOp")?; 2952 let addr = self.match_value("expected SSA value address")?; 2953 self.match_token(Token::Comma, "expected ',' between operands")?; 2954 let arg2 = self.match_value("expected SSA value address")?; 2955 InstructionData::AtomicRmw { 2956 opcode, 2957 flags, 2958 op, 2959 args: [addr, arg2], 2960 } 2961 } 2962 InstructionFormat::LoadNoOffset => { 2963 let flags = self.optional_memflags(); 2964 let addr = self.match_value("expected SSA value address")?; 2965 InstructionData::LoadNoOffset { 2966 opcode, 2967 flags, 2968 arg: addr, 2969 } 2970 } 2971 InstructionFormat::StoreNoOffset => { 2972 let flags = self.optional_memflags(); 2973 let arg = self.match_value("expected SSA value operand")?; 2974 self.match_token(Token::Comma, "expected ',' between operands")?; 2975 let addr = self.match_value("expected SSA value address")?; 2976 InstructionData::StoreNoOffset { 2977 opcode, 2978 flags, 2979 args: [arg, addr], 2980 } 2981 } 2982 }; 2983 Ok(idata) 2984 } 2985 } 2986 2987 #[cfg(test)] 2988 mod tests { 2989 use super::*; 2990 use crate::error::ParseError; 2991 use crate::isaspec::IsaSpec; 2992 use crate::testfile::{Comment, Details}; 2993 use cranelift_codegen::ir::entities::AnyEntity; 2994 use cranelift_codegen::ir::types; 2995 use cranelift_codegen::ir::StackSlotKind; 2996 use cranelift_codegen::ir::{ArgumentExtension, ArgumentPurpose}; 2997 use cranelift_codegen::isa::CallConv; 2998 2999 #[test] 3000 fn argument_type() { 3001 let mut p = Parser::new("i32 sext"); 3002 let arg = p.parse_abi_param().unwrap(); 3003 assert_eq!(arg.value_type, types::I32); 3004 assert_eq!(arg.extension, ArgumentExtension::Sext); 3005 assert_eq!(arg.purpose, ArgumentPurpose::Normal); 3006 let ParseError { 3007 location, 3008 message, 3009 is_warning, 3010 } = p.parse_abi_param().unwrap_err(); 3011 assert_eq!(location.line_number, 1); 3012 assert_eq!(message, "expected parameter type"); 3013 assert!(!is_warning); 3014 } 3015 3016 #[test] 3017 fn aliases() { 3018 let (func, details) = Parser::new( 3019 "function %qux() system_v { 3020 block0: 3021 v4 = iconst.i8 6 3022 v3 -> v4 3023 v1 = iadd_imm v3, 17 3024 }", 3025 ) 3026 .parse_function() 3027 .unwrap(); 3028 assert_eq!(func.name.to_string(), "%qux"); 3029 let v4 = details.map.lookup_str("v4").unwrap(); 3030 assert_eq!(v4.to_string(), "v4"); 3031 let v3 = details.map.lookup_str("v3").unwrap(); 3032 assert_eq!(v3.to_string(), "v3"); 3033 match v3 { 3034 AnyEntity::Value(v3) => { 3035 let aliased_to = func.dfg.resolve_aliases(v3); 3036 assert_eq!(aliased_to.to_string(), "v4"); 3037 } 3038 _ => panic!("expected value: {}", v3), 3039 } 3040 } 3041 3042 #[test] 3043 fn signature() { 3044 let sig = Parser::new("()system_v").parse_signature().unwrap(); 3045 assert_eq!(sig.params.len(), 0); 3046 assert_eq!(sig.returns.len(), 0); 3047 assert_eq!(sig.call_conv, CallConv::SystemV); 3048 3049 let sig2 = Parser::new("(i8 uext, f32, f64, i32 sret) -> i32 sext, f64 baldrdash_system_v") 3050 .parse_signature() 3051 .unwrap(); 3052 assert_eq!( 3053 sig2.to_string(), 3054 "(i8 uext, f32, f64, i32 sret) -> i32 sext, f64 baldrdash_system_v" 3055 ); 3056 assert_eq!(sig2.call_conv, CallConv::BaldrdashSystemV); 3057 3058 // Old-style signature without a calling convention. 3059 assert_eq!( 3060 Parser::new("()").parse_signature().unwrap().to_string(), 3061 "() fast" 3062 ); 3063 assert_eq!( 3064 Parser::new("() notacc") 3065 .parse_signature() 3066 .unwrap_err() 3067 .to_string(), 3068 "1: unknown calling convention: notacc" 3069 ); 3070 3071 // `void` is not recognized as a type by the lexer. It should not appear in files. 3072 assert_eq!( 3073 Parser::new("() -> void") 3074 .parse_signature() 3075 .unwrap_err() 3076 .to_string(), 3077 "1: expected parameter type" 3078 ); 3079 assert_eq!( 3080 Parser::new("i8 -> i8") 3081 .parse_signature() 3082 .unwrap_err() 3083 .to_string(), 3084 "1: expected function signature: ( args... )" 3085 ); 3086 assert_eq!( 3087 Parser::new("(i8 -> i8") 3088 .parse_signature() 3089 .unwrap_err() 3090 .to_string(), 3091 "1: expected ')' after function arguments" 3092 ); 3093 } 3094 3095 #[test] 3096 fn stack_slot_decl() { 3097 let (func, _) = Parser::new( 3098 "function %foo() system_v { 3099 ss3 = explicit_slot 13 3100 ss1 = explicit_slot 1 3101 }", 3102 ) 3103 .parse_function() 3104 .unwrap(); 3105 assert_eq!(func.name.to_string(), "%foo"); 3106 let mut iter = func.stack_slots.keys(); 3107 let _ss0 = iter.next().unwrap(); 3108 let ss1 = iter.next().unwrap(); 3109 assert_eq!(ss1.to_string(), "ss1"); 3110 assert_eq!(func.stack_slots[ss1].kind, StackSlotKind::ExplicitSlot); 3111 assert_eq!(func.stack_slots[ss1].size, 1); 3112 let _ss2 = iter.next().unwrap(); 3113 let ss3 = iter.next().unwrap(); 3114 assert_eq!(ss3.to_string(), "ss3"); 3115 assert_eq!(func.stack_slots[ss3].kind, StackSlotKind::ExplicitSlot); 3116 assert_eq!(func.stack_slots[ss3].size, 13); 3117 assert_eq!(iter.next(), None); 3118 3119 // Catch duplicate definitions. 3120 assert_eq!( 3121 Parser::new( 3122 "function %bar() system_v { 3123 ss1 = explicit_slot 13 3124 ss1 = explicit_slot 1 3125 }", 3126 ) 3127 .parse_function() 3128 .unwrap_err() 3129 .to_string(), 3130 "3: duplicate entity: ss1" 3131 ); 3132 } 3133 3134 #[test] 3135 fn block_header() { 3136 let (func, _) = Parser::new( 3137 "function %blocks() system_v { 3138 block0: 3139 block4(v3: i32): 3140 }", 3141 ) 3142 .parse_function() 3143 .unwrap(); 3144 assert_eq!(func.name.to_string(), "%blocks"); 3145 3146 let mut blocks = func.layout.blocks(); 3147 3148 let block0 = blocks.next().unwrap(); 3149 assert_eq!(func.dfg.block_params(block0), &[]); 3150 3151 let block4 = blocks.next().unwrap(); 3152 let block4_args = func.dfg.block_params(block4); 3153 assert_eq!(block4_args.len(), 1); 3154 assert_eq!(func.dfg.value_type(block4_args[0]), types::I32); 3155 } 3156 3157 #[test] 3158 fn duplicate_block() { 3159 let ParseError { 3160 location, 3161 message, 3162 is_warning, 3163 } = Parser::new( 3164 "function %blocks() system_v { 3165 block0: 3166 block0: 3167 return 2", 3168 ) 3169 .parse_function() 3170 .unwrap_err(); 3171 3172 assert_eq!(location.line_number, 3); 3173 assert_eq!(message, "duplicate entity: block0"); 3174 assert!(!is_warning); 3175 } 3176 3177 #[test] 3178 fn number_of_blocks() { 3179 let ParseError { 3180 location, 3181 message, 3182 is_warning, 3183 } = Parser::new( 3184 "function %a() { 3185 block100000:", 3186 ) 3187 .parse_function() 3188 .unwrap_err(); 3189 3190 assert_eq!(location.line_number, 2); 3191 assert_eq!(message, "too many blocks"); 3192 assert!(!is_warning); 3193 } 3194 3195 #[test] 3196 fn duplicate_jt() { 3197 let ParseError { 3198 location, 3199 message, 3200 is_warning, 3201 } = Parser::new( 3202 "function %blocks() system_v { 3203 jt0 = jump_table [] 3204 jt0 = jump_table []", 3205 ) 3206 .parse_function() 3207 .unwrap_err(); 3208 3209 assert_eq!(location.line_number, 3); 3210 assert_eq!(message, "duplicate entity: jt0"); 3211 assert!(!is_warning); 3212 } 3213 3214 #[test] 3215 fn duplicate_ss() { 3216 let ParseError { 3217 location, 3218 message, 3219 is_warning, 3220 } = Parser::new( 3221 "function %blocks() system_v { 3222 ss0 = explicit_slot 8 3223 ss0 = explicit_slot 8", 3224 ) 3225 .parse_function() 3226 .unwrap_err(); 3227 3228 assert_eq!(location.line_number, 3); 3229 assert_eq!(message, "duplicate entity: ss0"); 3230 assert!(!is_warning); 3231 } 3232 3233 #[test] 3234 fn duplicate_gv() { 3235 let ParseError { 3236 location, 3237 message, 3238 is_warning, 3239 } = Parser::new( 3240 "function %blocks() system_v { 3241 gv0 = vmctx 3242 gv0 = vmctx", 3243 ) 3244 .parse_function() 3245 .unwrap_err(); 3246 3247 assert_eq!(location.line_number, 3); 3248 assert_eq!(message, "duplicate entity: gv0"); 3249 assert!(!is_warning); 3250 } 3251 3252 #[test] 3253 fn duplicate_heap() { 3254 let ParseError { 3255 location, 3256 message, 3257 is_warning, 3258 } = Parser::new( 3259 "function %blocks() system_v { 3260 heap0 = static gv0, min 0x1000, bound 0x10_0000, offset_guard 0x1000 3261 heap0 = static gv0, min 0x1000, bound 0x10_0000, offset_guard 0x1000", 3262 ) 3263 .parse_function() 3264 .unwrap_err(); 3265 3266 assert_eq!(location.line_number, 3); 3267 assert_eq!(message, "duplicate entity: heap0"); 3268 assert!(!is_warning); 3269 } 3270 3271 #[test] 3272 fn duplicate_sig() { 3273 let ParseError { 3274 location, 3275 message, 3276 is_warning, 3277 } = Parser::new( 3278 "function %blocks() system_v { 3279 sig0 = () 3280 sig0 = ()", 3281 ) 3282 .parse_function() 3283 .unwrap_err(); 3284 3285 assert_eq!(location.line_number, 3); 3286 assert_eq!(message, "duplicate entity: sig0"); 3287 assert!(!is_warning); 3288 } 3289 3290 #[test] 3291 fn duplicate_fn() { 3292 let ParseError { 3293 location, 3294 message, 3295 is_warning, 3296 } = Parser::new( 3297 "function %blocks() system_v { 3298 sig0 = () 3299 fn0 = %foo sig0 3300 fn0 = %foo sig0", 3301 ) 3302 .parse_function() 3303 .unwrap_err(); 3304 3305 assert_eq!(location.line_number, 4); 3306 assert_eq!(message, "duplicate entity: fn0"); 3307 assert!(!is_warning); 3308 } 3309 3310 #[test] 3311 fn comments() { 3312 let (func, Details { comments, .. }) = Parser::new( 3313 "; before 3314 function %comment() system_v { ; decl 3315 ss10 = explicit_slot 13 ; stackslot. 3316 ; Still stackslot. 3317 jt10 = jump_table [block0] 3318 ; Jumptable 3319 block0: ; Basic block 3320 trap user42; Instruction 3321 } ; Trailing. 3322 ; More trailing.", 3323 ) 3324 .parse_function() 3325 .unwrap(); 3326 assert_eq!(func.name.to_string(), "%comment"); 3327 assert_eq!(comments.len(), 8); // no 'before' comment. 3328 assert_eq!( 3329 comments[0], 3330 Comment { 3331 entity: AnyEntity::Function, 3332 text: "; decl", 3333 } 3334 ); 3335 assert_eq!(comments[1].entity.to_string(), "ss10"); 3336 assert_eq!(comments[2].entity.to_string(), "ss10"); 3337 assert_eq!(comments[2].text, "; Still stackslot."); 3338 assert_eq!(comments[3].entity.to_string(), "jt10"); 3339 assert_eq!(comments[3].text, "; Jumptable"); 3340 assert_eq!(comments[4].entity.to_string(), "block0"); 3341 assert_eq!(comments[4].text, "; Basic block"); 3342 3343 assert_eq!(comments[5].entity.to_string(), "inst0"); 3344 assert_eq!(comments[5].text, "; Instruction"); 3345 3346 assert_eq!(comments[6].entity, AnyEntity::Function); 3347 assert_eq!(comments[7].entity, AnyEntity::Function); 3348 } 3349 3350 #[test] 3351 fn test_file() { 3352 let tf = parse_test( 3353 r#"; before 3354 test cfg option=5 3355 test verify 3356 set enable_float=false 3357 feature "foo" 3358 feature !"bar" 3359 ; still preamble 3360 function %comment() system_v {}"#, 3361 ParseOptions::default(), 3362 ) 3363 .unwrap(); 3364 assert_eq!(tf.commands.len(), 2); 3365 assert_eq!(tf.commands[0].command, "cfg"); 3366 assert_eq!(tf.commands[1].command, "verify"); 3367 match tf.isa_spec { 3368 IsaSpec::None(s) => { 3369 assert!(s.enable_verifier()); 3370 assert!(!s.enable_float()); 3371 } 3372 _ => panic!("unexpected ISAs"), 3373 } 3374 assert_eq!(tf.features[0], Feature::With(&"foo")); 3375 assert_eq!(tf.features[1], Feature::Without(&"bar")); 3376 assert_eq!(tf.preamble_comments.len(), 2); 3377 assert_eq!(tf.preamble_comments[0].text, "; before"); 3378 assert_eq!(tf.preamble_comments[1].text, "; still preamble"); 3379 assert_eq!(tf.functions.len(), 1); 3380 assert_eq!(tf.functions[0].0.name.to_string(), "%comment"); 3381 } 3382 3383 #[test] 3384 fn isa_spec() { 3385 assert!(parse_test( 3386 "target 3387 function %foo() system_v {}", 3388 ParseOptions::default() 3389 ) 3390 .is_err()); 3391 3392 assert!(parse_test( 3393 "target x86_64 3394 set enable_float=false 3395 function %foo() system_v {}", 3396 ParseOptions::default() 3397 ) 3398 .is_err()); 3399 3400 match parse_test( 3401 "set enable_float=false 3402 target x86_64 3403 function %foo() system_v {}", 3404 ParseOptions::default(), 3405 ) 3406 .unwrap() 3407 .isa_spec 3408 { 3409 IsaSpec::None(_) => panic!("Expected some ISA"), 3410 IsaSpec::Some(v) => { 3411 assert_eq!(v.len(), 1); 3412 assert!(v[0].name() == "x64" || v[0].name() == "x86"); 3413 } 3414 } 3415 } 3416 3417 #[test] 3418 fn user_function_name() { 3419 // Valid characters in the name: 3420 let func = Parser::new( 3421 "function u1:2() system_v { 3422 block0: 3423 trap int_divz 3424 }", 3425 ) 3426 .parse_function() 3427 .unwrap() 3428 .0; 3429 assert_eq!(func.name.to_string(), "u1:2"); 3430 3431 // Invalid characters in the name: 3432 let mut parser = Parser::new( 3433 "function u123:abc() system_v { 3434 block0: 3435 trap stk_ovf 3436 }", 3437 ); 3438 assert!(parser.parse_function().is_err()); 3439 3440 // Incomplete function names should not be valid: 3441 let mut parser = Parser::new( 3442 "function u() system_v { 3443 block0: 3444 trap int_ovf 3445 }", 3446 ); 3447 assert!(parser.parse_function().is_err()); 3448 3449 let mut parser = Parser::new( 3450 "function u0() system_v { 3451 block0: 3452 trap int_ovf 3453 }", 3454 ); 3455 assert!(parser.parse_function().is_err()); 3456 3457 let mut parser = Parser::new( 3458 "function u0:() system_v { 3459 block0: 3460 trap int_ovf 3461 }", 3462 ); 3463 assert!(parser.parse_function().is_err()); 3464 } 3465 3466 #[test] 3467 fn change_default_calling_convention() { 3468 let code = "function %test() { 3469 block0: 3470 return 3471 }"; 3472 3473 // By default the parser will use the fast calling convention if none is specified. 3474 let mut parser = Parser::new(code); 3475 assert_eq!( 3476 parser.parse_function().unwrap().0.signature.call_conv, 3477 CallConv::Fast 3478 ); 3479 3480 // However, we can specify a different calling convention to be the default. 3481 let mut parser = Parser::new(code).with_default_calling_convention(CallConv::Cold); 3482 assert_eq!( 3483 parser.parse_function().unwrap().0.signature.call_conv, 3484 CallConv::Cold 3485 ); 3486 } 3487 3488 #[test] 3489 fn u8_as_hex() { 3490 fn parse_as_uimm8(text: &str) -> ParseResult<u8> { 3491 Parser::new(text).match_uimm8("unable to parse u8") 3492 } 3493 3494 assert_eq!(parse_as_uimm8("0").unwrap(), 0); 3495 assert_eq!(parse_as_uimm8("0xff").unwrap(), 255); 3496 assert!(parse_as_uimm8("-1").is_err()); 3497 assert!(parse_as_uimm8("0xffa").is_err()); 3498 } 3499 3500 #[test] 3501 fn i16_as_hex() { 3502 fn parse_as_imm16(text: &str) -> ParseResult<i16> { 3503 Parser::new(text).match_imm16("unable to parse i16") 3504 } 3505 3506 assert_eq!(parse_as_imm16("0x8000").unwrap(), -32768); 3507 assert_eq!(parse_as_imm16("0xffff").unwrap(), -1); 3508 assert_eq!(parse_as_imm16("0").unwrap(), 0); 3509 assert_eq!(parse_as_imm16("0x7fff").unwrap(), 32767); 3510 assert_eq!( 3511 parse_as_imm16("-0x0001").unwrap(), 3512 parse_as_imm16("0xffff").unwrap() 3513 ); 3514 assert_eq!( 3515 parse_as_imm16("-0x7fff").unwrap(), 3516 parse_as_imm16("0x8001").unwrap() 3517 ); 3518 assert!(parse_as_imm16("0xffffa").is_err()); 3519 } 3520 3521 #[test] 3522 fn i32_as_hex() { 3523 fn parse_as_imm32(text: &str) -> ParseResult<i32> { 3524 Parser::new(text).match_imm32("unable to parse i32") 3525 } 3526 3527 assert_eq!(parse_as_imm32("0x80000000").unwrap(), -2147483648); 3528 assert_eq!(parse_as_imm32("0xffffffff").unwrap(), -1); 3529 assert_eq!(parse_as_imm32("0").unwrap(), 0); 3530 assert_eq!(parse_as_imm32("0x7fffffff").unwrap(), 2147483647); 3531 assert_eq!( 3532 parse_as_imm32("-0x00000001").unwrap(), 3533 parse_as_imm32("0xffffffff").unwrap() 3534 ); 3535 assert_eq!( 3536 parse_as_imm32("-0x7fffffff").unwrap(), 3537 parse_as_imm32("0x80000001").unwrap() 3538 ); 3539 assert!(parse_as_imm32("0xffffffffa").is_err()); 3540 } 3541 3542 #[test] 3543 fn i64_as_hex() { 3544 fn parse_as_imm64(text: &str) -> ParseResult<Imm64> { 3545 Parser::new(text).match_imm64("unable to parse Imm64") 3546 } 3547 3548 assert_eq!( 3549 parse_as_imm64("0x8000000000000000").unwrap(), 3550 Imm64::new(-9223372036854775808) 3551 ); 3552 assert_eq!( 3553 parse_as_imm64("0xffffffffffffffff").unwrap(), 3554 Imm64::new(-1) 3555 ); 3556 assert_eq!(parse_as_imm64("0").unwrap(), Imm64::new(0)); 3557 assert_eq!( 3558 parse_as_imm64("0x7fffffffffffffff").unwrap(), 3559 Imm64::new(9223372036854775807) 3560 ); 3561 assert_eq!( 3562 parse_as_imm64("-0x0000000000000001").unwrap(), 3563 parse_as_imm64("0xffffffffffffffff").unwrap() 3564 ); 3565 assert_eq!( 3566 parse_as_imm64("-0x7fffffffffffffff").unwrap(), 3567 parse_as_imm64("0x8000000000000001").unwrap() 3568 ); 3569 assert!(parse_as_imm64("0xffffffffffffffffa").is_err()); 3570 } 3571 3572 #[test] 3573 fn uimm128() { 3574 macro_rules! parse_as_constant_data { 3575 ($text:expr, $type:expr) => {{ 3576 Parser::new($text).parse_literals_to_constant_data($type) 3577 }}; 3578 } 3579 macro_rules! can_parse_as_constant_data { 3580 ($text:expr, $type:expr) => {{ 3581 assert!(parse_as_constant_data!($text, $type).is_ok()) 3582 }}; 3583 } 3584 macro_rules! cannot_parse_as_constant_data { 3585 ($text:expr, $type:expr) => {{ 3586 assert!(parse_as_constant_data!($text, $type).is_err()) 3587 }}; 3588 } 3589 3590 can_parse_as_constant_data!("1 2 3 4", I32X4); 3591 can_parse_as_constant_data!("1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16", I8X16); 3592 can_parse_as_constant_data!("0x1.1 0x2.2 0x3.3 0x4.4", F32X4); 3593 can_parse_as_constant_data!("0x0 0x1 0x2 0x3", I32X4); 3594 can_parse_as_constant_data!("true false true false true false true false", B16X8); 3595 can_parse_as_constant_data!("0 -1", I64X2); 3596 can_parse_as_constant_data!("true false", B64X2); 3597 can_parse_as_constant_data!("true true true true true", B32X4); // note that parse_literals_to_constant_data will leave extra tokens unconsumed 3598 3599 cannot_parse_as_constant_data!("1 2 3", I32X4); 3600 cannot_parse_as_constant_data!(" ", F32X4); 3601 } 3602 3603 #[test] 3604 fn parse_constant_from_booleans() { 3605 let c = Parser::new("true false true false") 3606 .parse_literals_to_constant_data(B32X4) 3607 .unwrap(); 3608 assert_eq!( 3609 c.into_vec(), 3610 [0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0] 3611 ) 3612 } 3613 3614 #[test] 3615 fn parse_unbounded_constants() { 3616 // Unlike match_uimm128, match_constant_data can parse byte sequences of any size: 3617 assert_eq!( 3618 Parser::new("[0 1]").match_constant_data().unwrap(), 3619 vec![0, 1].into() 3620 ); 3621 3622 // Only parse byte literals: 3623 assert!(Parser::new("[256]").match_constant_data().is_err()); 3624 } 3625 3626 #[test] 3627 fn parse_run_commands() { 3628 // Helper for creating signatures. 3629 fn sig(ins: &[Type], outs: &[Type]) -> Signature { 3630 let mut sig = Signature::new(CallConv::Fast); 3631 for i in ins { 3632 sig.params.push(AbiParam::new(*i)); 3633 } 3634 for o in outs { 3635 sig.returns.push(AbiParam::new(*o)); 3636 } 3637 sig 3638 } 3639 3640 // Helper for parsing run commands. 3641 fn parse(text: &str, sig: &Signature) -> ParseResult<RunCommand> { 3642 Parser::new(text).parse_run_command(sig) 3643 } 3644 3645 // Check that we can parse and display the same set of run commands. 3646 fn assert_roundtrip(text: &str, sig: &Signature) { 3647 assert_eq!(parse(text, sig).unwrap().to_string(), text); 3648 } 3649 assert_roundtrip("run: %fn0() == 42", &sig(&[], &[I32])); 3650 assert_roundtrip( 3651 "run: %fn0(8, 16, 32, 64) == true", 3652 &sig(&[I8, I16, I32, I64], &[B8]), 3653 ); 3654 assert_roundtrip( 3655 "run: %my_func(true) == 0x0f0e0d0c0b0a09080706050403020100", 3656 &sig(&[B32], &[I8X16]), 3657 ); 3658 3659 // Verify that default invocations are created when not specified. 3660 assert_eq!( 3661 parse("run", &sig(&[], &[B32])).unwrap().to_string(), 3662 "run: %default() == true" 3663 ); 3664 assert_eq!( 3665 parse("print", &sig(&[], &[F32X4, I16X8])) 3666 .unwrap() 3667 .to_string(), 3668 "print: %default()" 3669 ); 3670 3671 // Demonstrate some unparseable cases. 3672 assert!(parse("print", &sig(&[I32], &[B32])).is_err()); 3673 assert!(parse("run", &sig(&[], &[I32])).is_err()); 3674 assert!(parse("print:", &sig(&[], &[])).is_err()); 3675 assert!(parse("run: ", &sig(&[], &[])).is_err()); 3676 } 3677 3678 #[test] 3679 fn parse_heap_commands() { 3680 fn parse(text: &str) -> ParseResult<HeapCommand> { 3681 Parser::new(text).parse_heap_command() 3682 } 3683 3684 // Check that we can parse and display the same set of heap commands. 3685 fn assert_roundtrip(text: &str) { 3686 assert_eq!(parse(text).unwrap().to_string(), text); 3687 } 3688 3689 assert_roundtrip("heap: static, size=10"); 3690 assert_roundtrip("heap: dynamic, size=10"); 3691 assert_roundtrip("heap: static, size=10, ptr=vmctx+10"); 3692 assert_roundtrip("heap: static, size=10, bound=vmctx+11"); 3693 assert_roundtrip("heap: static, size=10, ptr=vmctx+10, bound=vmctx+10"); 3694 assert_roundtrip("heap: dynamic, size=10, ptr=vmctx+10"); 3695 assert_roundtrip("heap: dynamic, size=10, bound=vmctx+11"); 3696 assert_roundtrip("heap: dynamic, size=10, ptr=vmctx+10, bound=vmctx+10"); 3697 3698 let static_heap = parse("heap: static, size=10, ptr=vmctx+8, bound=vmctx+2").unwrap(); 3699 assert_eq!(static_heap.size, Uimm64::new(10)); 3700 assert_eq!(static_heap.heap_type, HeapType::Static); 3701 assert_eq!(static_heap.ptr_offset, Some(Uimm64::new(8))); 3702 assert_eq!(static_heap.bound_offset, Some(Uimm64::new(2))); 3703 let dynamic_heap = parse("heap: dynamic, size=0x10").unwrap(); 3704 assert_eq!(dynamic_heap.size, Uimm64::new(16)); 3705 assert_eq!(dynamic_heap.heap_type, HeapType::Dynamic); 3706 assert_eq!(dynamic_heap.ptr_offset, None); 3707 assert_eq!(dynamic_heap.bound_offset, None); 3708 3709 assert!(parse("heap: static").is_err()); 3710 assert!(parse("heap: dynamic").is_err()); 3711 assert!(parse("heap: static size=0").is_err()); 3712 assert!(parse("heap: dynamic size=0").is_err()); 3713 assert!(parse("heap: static, size=10, ptr=10").is_err()); 3714 assert!(parse("heap: static, size=10, bound=vmctx-10").is_err()); 3715 } 3716 3717 #[test] 3718 fn parse_data_values() { 3719 fn parse(text: &str, ty: Type) -> DataValue { 3720 Parser::new(text).parse_data_value(ty).unwrap() 3721 } 3722 3723 assert_eq!(parse("8", I8).to_string(), "8"); 3724 assert_eq!(parse("16", I16).to_string(), "16"); 3725 assert_eq!(parse("32", I32).to_string(), "32"); 3726 assert_eq!(parse("64", I64).to_string(), "64"); 3727 assert_eq!( 3728 parse("0x01234567_01234567_01234567_01234567", I128).to_string(), 3729 "1512366032949150931280199141537564007" 3730 ); 3731 assert_eq!(parse("1234567", I128).to_string(), "1234567"); 3732 assert_eq!(parse("0x32.32", F32).to_string(), "0x1.919000p5"); 3733 assert_eq!(parse("0x64.64", F64).to_string(), "0x1.9190000000000p6"); 3734 assert_eq!(parse("true", B1).to_string(), "true"); 3735 assert_eq!(parse("false", B64).to_string(), "false"); 3736 assert_eq!( 3737 parse("[0 1 2 3]", I32X4).to_string(), 3738 "0x00000003000000020000000100000000" 3739 ); 3740 } 3741 3742 #[test] 3743 fn parse_cold_blocks() { 3744 let code = "function %test() { 3745 block0 cold: 3746 return 3747 block1(v0: i32) cold: 3748 return 3749 block2(v1: i32): 3750 return 3751 }"; 3752 3753 let mut parser = Parser::new(code); 3754 let func = parser.parse_function().unwrap().0; 3755 assert_eq!(func.layout.blocks().count(), 3); 3756 assert!(func.layout.is_cold(Block::from_u32(0))); 3757 assert!(func.layout.is_cold(Block::from_u32(1))); 3758 assert!(!func.layout.is_cold(Block::from_u32(2))); 3759 } 3760 } 3761