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