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