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