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 match self.token() { 1351 Some(Token::Identifier(text)) => 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 Some(Token::Cold) => { 1360 self.consume(); 1361 sig.call_conv = CallConv::Cold; 1362 } 1363 _ => {} 1364 } 1365 1366 Ok(sig) 1367 } 1368 1369 // Parse list of function parameter / return value types. 1370 // 1371 // paramlist ::= * param { "," param } 1372 // 1373 fn parse_abi_param_list(&mut self) -> ParseResult<Vec<AbiParam>> { 1374 let mut list = Vec::new(); 1375 1376 // abi-param-list ::= * abi-param { "," abi-param } 1377 list.push(self.parse_abi_param()?); 1378 1379 // abi-param-list ::= abi-param * { "," abi-param } 1380 while self.optional(Token::Comma) { 1381 // abi-param-list ::= abi-param { "," * abi-param } 1382 list.push(self.parse_abi_param()?); 1383 } 1384 1385 Ok(list) 1386 } 1387 1388 // Parse a single argument type with flags. 1389 fn parse_abi_param(&mut self) -> ParseResult<AbiParam> { 1390 // abi-param ::= * type { flag } 1391 let mut arg = AbiParam::new(self.match_type("expected parameter type")?); 1392 1393 // abi-param ::= type * { flag } 1394 while let Some(Token::Identifier(s)) = self.token() { 1395 match s { 1396 "uext" => arg.extension = ArgumentExtension::Uext, 1397 "sext" => arg.extension = ArgumentExtension::Sext, 1398 "sarg" => { 1399 self.consume(); 1400 self.match_token(Token::LPar, "expected '(' to begin sarg size")?; 1401 let size = self.match_uimm32("expected byte-size in sarg decl")?; 1402 self.match_token(Token::RPar, "expected ')' to end sarg size")?; 1403 arg.purpose = ArgumentPurpose::StructArgument(size.into()); 1404 continue; 1405 } 1406 _ => { 1407 if let Ok(purpose) = s.parse() { 1408 arg.purpose = purpose; 1409 } else { 1410 break; 1411 } 1412 } 1413 } 1414 self.consume(); 1415 } 1416 1417 Ok(arg) 1418 } 1419 1420 // Parse the function preamble. 1421 // 1422 // preamble ::= * { preamble-decl } 1423 // preamble-decl ::= * stack-slot-decl 1424 // * function-decl 1425 // * signature-decl 1426 // * jump-table-decl 1427 // * stack-limit-decl 1428 // 1429 // The parsed decls are added to `ctx` rather than returned. 1430 fn parse_preamble(&mut self, ctx: &mut Context) -> ParseResult<()> { 1431 loop { 1432 match self.token() { 1433 Some(Token::StackSlot(..)) => { 1434 self.start_gathering_comments(); 1435 let loc = self.loc; 1436 self.parse_stack_slot_decl() 1437 .and_then(|(ss, dat)| ctx.add_ss(ss, dat, loc)) 1438 } 1439 Some(Token::DynamicStackSlot(..)) => { 1440 self.start_gathering_comments(); 1441 let loc = self.loc; 1442 self.parse_dynamic_stack_slot_decl() 1443 .and_then(|(dss, dat)| ctx.add_dss(dss, dat, loc)) 1444 } 1445 Some(Token::DynamicType(..)) => { 1446 self.start_gathering_comments(); 1447 let loc = self.loc; 1448 self.parse_dynamic_type_decl() 1449 .and_then(|(dt, dat)| ctx.add_dt(dt, dat, loc)) 1450 } 1451 Some(Token::GlobalValue(..)) => { 1452 self.start_gathering_comments(); 1453 self.parse_global_value_decl() 1454 .and_then(|(gv, dat, maybe_fact)| ctx.add_gv(gv, dat, maybe_fact, self.loc)) 1455 } 1456 Some(Token::MemoryType(..)) => { 1457 self.start_gathering_comments(); 1458 self.parse_memory_type_decl() 1459 .and_then(|(mt, dat)| ctx.add_mt(mt, dat, self.loc)) 1460 } 1461 Some(Token::SigRef(..)) => { 1462 self.start_gathering_comments(); 1463 self.parse_signature_decl().and_then(|(sig, dat)| { 1464 ctx.add_sig(sig, dat, self.loc, self.default_calling_convention) 1465 }) 1466 } 1467 Some(Token::FuncRef(..)) => { 1468 self.start_gathering_comments(); 1469 self.parse_function_decl(ctx) 1470 .and_then(|(fn_, dat)| ctx.add_fn(fn_, dat, self.loc)) 1471 } 1472 Some(Token::Constant(..)) => { 1473 self.start_gathering_comments(); 1474 self.parse_constant_decl() 1475 .and_then(|(c, v)| ctx.add_constant(c, v, self.loc)) 1476 } 1477 Some(Token::Identifier("stack_limit")) => { 1478 self.start_gathering_comments(); 1479 self.parse_stack_limit_decl() 1480 .and_then(|gv| ctx.add_stack_limit(gv, self.loc)) 1481 } 1482 // More to come.. 1483 _ => return Ok(()), 1484 }?; 1485 } 1486 } 1487 1488 // Parse a stack slot decl. 1489 // 1490 // stack-slot-decl ::= * StackSlot(ss) "=" stack-slot-kind Bytes {"," stack-slot-flag} 1491 // stack-slot-kind ::= "explicit_slot" 1492 // | "spill_slot" 1493 // | "incoming_arg" 1494 // | "outgoing_arg" 1495 // stack-slot-flag ::= "align" "=" Bytes 1496 fn parse_stack_slot_decl(&mut self) -> ParseResult<(StackSlot, StackSlotData)> { 1497 let ss = self.match_ss("expected stack slot number: ss«n»")?; 1498 self.match_token(Token::Equal, "expected '=' in stack slot declaration")?; 1499 let kind = self.match_enum("expected stack slot kind")?; 1500 1501 // stack-slot-decl ::= StackSlot(ss) "=" stack-slot-kind * Bytes {"," stack-slot-flag} 1502 let bytes: i64 = self 1503 .match_imm64("expected byte-size in stack_slot decl")? 1504 .into(); 1505 if bytes < 0 { 1506 return err!(self.loc, "negative stack slot size"); 1507 } 1508 if bytes > i64::from(u32::MAX) { 1509 return err!(self.loc, "stack slot too large"); 1510 } 1511 1512 // Parse flags. 1513 let align = if self.token() == Some(Token::Comma) { 1514 self.consume(); 1515 self.match_token( 1516 Token::Identifier("align"), 1517 "expected a valid stack-slot flag (currently only `align`)", 1518 )?; 1519 self.match_token(Token::Equal, "expected `=` after flag")?; 1520 let align: i64 = self 1521 .match_imm64("expected alignment-size after `align` flag")? 1522 .into(); 1523 u32::try_from(align) 1524 .map_err(|_| self.error("alignment must be a 32-bit unsigned integer"))? 1525 } else { 1526 1 1527 }; 1528 1529 if !align.is_power_of_two() { 1530 return err!(self.loc, "stack slot alignment is not a power of two"); 1531 } 1532 let align_shift = u8::try_from(align.ilog2()).unwrap(); // Always succeeds: range 0..=31. 1533 1534 let data = StackSlotData::new(kind, bytes as u32, align_shift); 1535 1536 // Collect any trailing comments. 1537 self.token(); 1538 self.claim_gathered_comments(ss); 1539 1540 // TBD: stack-slot-decl ::= StackSlot(ss) "=" stack-slot-kind Bytes * {"," stack-slot-flag} 1541 Ok((ss, data)) 1542 } 1543 1544 fn parse_dynamic_stack_slot_decl( 1545 &mut self, 1546 ) -> ParseResult<(DynamicStackSlot, DynamicStackSlotData)> { 1547 let dss = self.match_dss("expected stack slot number: dss«n»")?; 1548 self.match_token(Token::Equal, "expected '=' in stack slot declaration")?; 1549 let kind = self.match_enum("expected stack slot kind")?; 1550 let dt = self.match_dt("expected dynamic type")?; 1551 let data = DynamicStackSlotData::new(kind, dt); 1552 // Collect any trailing comments. 1553 self.token(); 1554 self.claim_gathered_comments(dss); 1555 1556 // TBD: stack-slot-decl ::= StackSlot(ss) "=" stack-slot-kind Bytes * {"," stack-slot-flag} 1557 Ok((dss, data)) 1558 } 1559 1560 fn parse_dynamic_type_decl(&mut self) -> ParseResult<(DynamicType, DynamicTypeData)> { 1561 let dt = self.match_dt("expected dynamic type number: dt«n»")?; 1562 self.match_token(Token::Equal, "expected '=' in stack slot declaration")?; 1563 let vector_base_ty = self.match_type("expected base type")?; 1564 assert!(vector_base_ty.is_vector(), "expected vector type"); 1565 self.match_token( 1566 Token::Multiply, 1567 "expected '*' followed by a dynamic scale value", 1568 )?; 1569 let dyn_scale = self.match_gv("expected dynamic scale global value")?; 1570 let data = DynamicTypeData::new(vector_base_ty, dyn_scale); 1571 // Collect any trailing comments. 1572 self.token(); 1573 self.claim_gathered_comments(dt); 1574 Ok((dt, data)) 1575 } 1576 1577 // Parse a global value decl. 1578 // 1579 // global-val-decl ::= * GlobalValue(gv) [ "!" fact ] "=" global-val-desc 1580 // global-val-desc ::= "vmctx" 1581 // | "load" "." type "notrap" "aligned" GlobalValue(base) [offset] 1582 // | "iadd_imm" "(" GlobalValue(base) ")" imm64 1583 // | "symbol" ["colocated"] name + imm64 1584 // | "dyn_scale_target_const" "." type 1585 // 1586 fn parse_global_value_decl( 1587 &mut self, 1588 ) -> ParseResult<(GlobalValue, GlobalValueData, Option<Fact>)> { 1589 let gv = self.match_gv("expected global value number: gv«n»")?; 1590 1591 let fact = if self.token() == Some(Token::Bang) { 1592 self.consume(); 1593 Some(self.parse_fact()?) 1594 } else { 1595 None 1596 }; 1597 1598 self.match_token(Token::Equal, "expected '=' in global value declaration")?; 1599 1600 let data = match self.match_any_identifier("expected global value kind")? { 1601 "vmctx" => GlobalValueData::VMContext, 1602 "load" => { 1603 self.match_token( 1604 Token::Dot, 1605 "expected '.' followed by type in load global value decl", 1606 )?; 1607 let global_type = self.match_type("expected load type")?; 1608 let flags = self.optional_memflags()?; 1609 let base = self.match_gv("expected global value: gv«n»")?; 1610 let offset = self.optional_offset32()?; 1611 1612 if !(flags.notrap() && flags.aligned()) { 1613 return err!(self.loc, "global-value load must be notrap and aligned"); 1614 } 1615 GlobalValueData::Load { 1616 base, 1617 offset, 1618 global_type, 1619 flags, 1620 } 1621 } 1622 "iadd_imm" => { 1623 self.match_token( 1624 Token::Dot, 1625 "expected '.' followed by type in iadd_imm global value decl", 1626 )?; 1627 let global_type = self.match_type("expected iadd type")?; 1628 let base = self.match_gv("expected global value: gv«n»")?; 1629 self.match_token( 1630 Token::Comma, 1631 "expected ',' followed by rhs in iadd_imm global value decl", 1632 )?; 1633 let offset = self.match_imm64("expected iadd_imm immediate")?; 1634 GlobalValueData::IAddImm { 1635 base, 1636 offset, 1637 global_type, 1638 } 1639 } 1640 "symbol" => { 1641 let colocated = self.optional(Token::Identifier("colocated")); 1642 let tls = self.optional(Token::Identifier("tls")); 1643 let name = self.parse_external_name()?; 1644 let offset = self.optional_offset_imm64()?; 1645 GlobalValueData::Symbol { 1646 name, 1647 offset, 1648 colocated, 1649 tls, 1650 } 1651 } 1652 "dyn_scale_target_const" => { 1653 self.match_token( 1654 Token::Dot, 1655 "expected '.' followed by type in dynamic scale global value decl", 1656 )?; 1657 let vector_type = self.match_type("expected load type")?; 1658 assert!(vector_type.is_vector(), "Expected vector type"); 1659 GlobalValueData::DynScaleTargetConst { vector_type } 1660 } 1661 other => return err!(self.loc, "Unknown global value kind '{}'", other), 1662 }; 1663 1664 // Collect any trailing comments. 1665 self.token(); 1666 self.claim_gathered_comments(gv); 1667 1668 Ok((gv, data, fact)) 1669 } 1670 1671 // Parse one field definition in a memory-type struct decl. 1672 // 1673 // memory-type-field ::= offset ":" type ["readonly"] [ "!" fact ] 1674 // offset ::= uimm64 1675 fn parse_memory_type_field(&mut self) -> ParseResult<MemoryTypeField> { 1676 let offset: u64 = self 1677 .match_uimm64( 1678 "expected u64 constant value for field offset in struct memory-type declaration", 1679 )? 1680 .into(); 1681 self.match_token( 1682 Token::Colon, 1683 "expected colon after field offset in struct memory-type declaration", 1684 )?; 1685 let ty = self.match_type("expected type for field in struct memory-type declaration")?; 1686 let readonly = if self.token() == Some(Token::Identifier("readonly")) { 1687 self.consume(); 1688 true 1689 } else { 1690 false 1691 }; 1692 let fact = if self.token() == Some(Token::Bang) { 1693 self.consume(); 1694 let fact = self.parse_fact()?; 1695 Some(fact) 1696 } else { 1697 None 1698 }; 1699 Ok(MemoryTypeField { 1700 offset, 1701 ty, 1702 readonly, 1703 fact, 1704 }) 1705 } 1706 1707 // Parse a memory-type decl. 1708 // 1709 // memory-type-decl ::= MemoryType(mt) "=" memory-type-desc 1710 // memory-type-desc ::= "struct" size "{" memory-type-field,* "}" 1711 // | "memory" size 1712 // | "dynamic_memory" GlobalValue "+" offset 1713 // | "empty" 1714 // size ::= uimm64 1715 // offset ::= uimm64 1716 fn parse_memory_type_decl(&mut self) -> ParseResult<(MemoryType, MemoryTypeData)> { 1717 let mt = self.match_mt("expected memory type number: mt«n»")?; 1718 self.match_token(Token::Equal, "expected '=' in memory type declaration")?; 1719 1720 let data = match self.token() { 1721 Some(Token::Identifier("struct")) => { 1722 self.consume(); 1723 let size: u64 = self.match_uimm64("expected u64 constant value for struct size in struct memory-type declaration")?.into(); 1724 self.match_token(Token::LBrace, "expected opening brace to start struct fields in struct memory-type declaration")?; 1725 let mut fields = vec![]; 1726 while self.token() != Some(Token::RBrace) { 1727 let field = self.parse_memory_type_field()?; 1728 fields.push(field); 1729 if self.token() == Some(Token::Comma) { 1730 self.consume(); 1731 } else { 1732 break; 1733 } 1734 } 1735 self.match_token( 1736 Token::RBrace, 1737 "expected closing brace after struct fields in struct memory-type declaration", 1738 )?; 1739 MemoryTypeData::Struct { size, fields } 1740 } 1741 Some(Token::Identifier("memory")) => { 1742 self.consume(); 1743 let size: u64 = self.match_uimm64("expected u64 constant value for size in static-memory memory-type declaration")?.into(); 1744 MemoryTypeData::Memory { size } 1745 } 1746 Some(Token::Identifier("dynamic_memory")) => { 1747 self.consume(); 1748 let gv = self.match_gv( 1749 "expected a global value for `dynamic_memory` memory-type declaration", 1750 )?; 1751 self.match_token( 1752 Token::Plus, 1753 "expected `+` after global value in `dynamic_memory` memory-type declaration", 1754 )?; 1755 let size: u64 = self.match_uimm64("expected u64 constant value for size offset in `dynamic_memory` memory-type declaration")?.into(); 1756 MemoryTypeData::DynamicMemory { gv, size } 1757 } 1758 Some(Token::Identifier("empty")) => { 1759 self.consume(); 1760 MemoryTypeData::Empty 1761 } 1762 other => { 1763 return err!( 1764 self.loc, 1765 "Unknown memory type declaration kind '{:?}'", 1766 other 1767 ) 1768 } 1769 }; 1770 1771 // Collect any trailing comments. 1772 self.token(); 1773 self.claim_gathered_comments(mt); 1774 1775 Ok((mt, data)) 1776 } 1777 1778 // Parse a signature decl. 1779 // 1780 // signature-decl ::= SigRef(sigref) "=" signature 1781 // 1782 fn parse_signature_decl(&mut self) -> ParseResult<(SigRef, Signature)> { 1783 let sig = self.match_sig("expected signature number: sig«n»")?; 1784 self.match_token(Token::Equal, "expected '=' in signature decl")?; 1785 let data = self.parse_signature()?; 1786 1787 // Collect any trailing comments. 1788 self.token(); 1789 self.claim_gathered_comments(sig); 1790 1791 Ok((sig, data)) 1792 } 1793 1794 // Parse a function decl. 1795 // 1796 // Two variants: 1797 // 1798 // function-decl ::= FuncRef(fnref) "=" ["colocated"]" name function-decl-sig 1799 // function-decl-sig ::= SigRef(sig) | signature 1800 // 1801 // The first variant allocates a new signature reference. The second references an existing 1802 // signature which must be declared first. 1803 // 1804 fn parse_function_decl(&mut self, ctx: &mut Context) -> ParseResult<(FuncRef, ExtFuncData)> { 1805 let fn_ = self.match_fn("expected function number: fn«n»")?; 1806 self.match_token(Token::Equal, "expected '=' in function decl")?; 1807 1808 let loc = self.loc; 1809 1810 // function-decl ::= FuncRef(fnref) "=" * ["colocated"] name function-decl-sig 1811 let colocated = self.optional(Token::Identifier("colocated")); 1812 1813 // function-decl ::= FuncRef(fnref) "=" ["colocated"] * name function-decl-sig 1814 let name = self.parse_external_name()?; 1815 1816 // function-decl ::= FuncRef(fnref) "=" ["colocated"] name * function-decl-sig 1817 let data = match self.token() { 1818 Some(Token::LPar) => { 1819 // function-decl ::= FuncRef(fnref) "=" ["colocated"] name * signature 1820 let sig = self.parse_signature()?; 1821 let sigref = ctx.function.import_signature(sig); 1822 ctx.map 1823 .def_entity(sigref.into(), loc) 1824 .expect("duplicate SigRef entities created"); 1825 ExtFuncData { 1826 name, 1827 signature: sigref, 1828 colocated, 1829 } 1830 } 1831 Some(Token::SigRef(sig_src)) => { 1832 let sig = match SigRef::with_number(sig_src) { 1833 None => { 1834 return err!(self.loc, "attempted to use invalid signature ss{}", sig_src); 1835 } 1836 Some(sig) => sig, 1837 }; 1838 ctx.check_sig(sig, self.loc)?; 1839 self.consume(); 1840 ExtFuncData { 1841 name, 1842 signature: sig, 1843 colocated, 1844 } 1845 } 1846 _ => return err!(self.loc, "expected 'function' or sig«n» in function decl"), 1847 }; 1848 1849 // Collect any trailing comments. 1850 self.token(); 1851 self.claim_gathered_comments(fn_); 1852 1853 Ok((fn_, data)) 1854 } 1855 1856 // Parse a jump table literal. 1857 // 1858 // jump-table-lit ::= "[" block(args) {"," block(args) } "]" 1859 // | "[]" 1860 fn parse_jump_table( 1861 &mut self, 1862 ctx: &mut Context, 1863 def: ir::BlockCall, 1864 ) -> ParseResult<ir::JumpTable> { 1865 self.match_token(Token::LBracket, "expected '[' before jump table contents")?; 1866 1867 let mut data = Vec::new(); 1868 1869 match self.token() { 1870 Some(Token::Block(dest)) => { 1871 self.consume(); 1872 let args = self.parse_opt_value_list()?; 1873 data.push(ctx.function.dfg.block_call(dest, &args)); 1874 1875 loop { 1876 match self.token() { 1877 Some(Token::Comma) => { 1878 self.consume(); 1879 if let Some(Token::Block(dest)) = self.token() { 1880 self.consume(); 1881 let args = self.parse_opt_value_list()?; 1882 data.push(ctx.function.dfg.block_call(dest, &args)); 1883 } else { 1884 return err!(self.loc, "expected jump_table entry"); 1885 } 1886 } 1887 Some(Token::RBracket) => break, 1888 _ => return err!(self.loc, "expected ']' after jump table contents"), 1889 } 1890 } 1891 } 1892 Some(Token::RBracket) => (), 1893 _ => return err!(self.loc, "expected jump_table entry"), 1894 } 1895 1896 self.consume(); 1897 1898 Ok(ctx 1899 .function 1900 .dfg 1901 .jump_tables 1902 .push(JumpTableData::new(def, &data))) 1903 } 1904 1905 // Parse a constant decl. 1906 // 1907 // constant-decl ::= * Constant(c) "=" ty? "[" literal {"," literal} "]" 1908 fn parse_constant_decl(&mut self) -> ParseResult<(Constant, ConstantData)> { 1909 let name = self.match_constant()?; 1910 self.match_token(Token::Equal, "expected '=' in constant decl")?; 1911 let data = if let Some(Token::Type(_)) = self.token() { 1912 let ty = self.match_type("expected type of constant")?; 1913 self.match_uimm128(ty) 1914 } else { 1915 self.match_hexadecimal_constant("expected an immediate hexadecimal operand") 1916 }?; 1917 1918 // Collect any trailing comments. 1919 self.token(); 1920 self.claim_gathered_comments(name); 1921 1922 Ok((name, data)) 1923 } 1924 1925 // Parse a stack limit decl 1926 // 1927 // stack-limit-decl ::= * StackLimit "=" GlobalValue(gv) 1928 fn parse_stack_limit_decl(&mut self) -> ParseResult<GlobalValue> { 1929 self.match_stack_limit()?; 1930 self.match_token(Token::Equal, "expected '=' in stack limit decl")?; 1931 let limit = match self.token() { 1932 Some(Token::GlobalValue(base_num)) => match GlobalValue::with_number(base_num) { 1933 Some(gv) => gv, 1934 None => return err!(self.loc, "invalid global value number for stack limit"), 1935 }, 1936 _ => return err!(self.loc, "expected global value"), 1937 }; 1938 self.consume(); 1939 1940 // Collect any trailing comments. 1941 self.token(); 1942 self.claim_gathered_comments(AnyEntity::StackLimit); 1943 1944 Ok(limit) 1945 } 1946 1947 // Parse a function body, add contents to `ctx`. 1948 // 1949 // function-body ::= * { extended-basic-block } 1950 // 1951 fn parse_function_body(&mut self, ctx: &mut Context) -> ParseResult<()> { 1952 while self.token() != Some(Token::RBrace) { 1953 self.parse_basic_block(ctx)?; 1954 } 1955 1956 // Now that we've seen all defined values in the function, ensure that 1957 // all references refer to a definition. 1958 for block in &ctx.function.layout { 1959 for inst in ctx.function.layout.block_insts(block) { 1960 for value in ctx.function.dfg.inst_values(inst) { 1961 if !ctx.map.contains_value(value) { 1962 return err!( 1963 ctx.map.location(AnyEntity::Inst(inst)).unwrap(), 1964 "undefined operand value {}", 1965 value 1966 ); 1967 } 1968 } 1969 } 1970 } 1971 1972 for alias in &ctx.aliases { 1973 if !ctx.function.dfg.set_alias_type_for_parser(*alias) { 1974 let loc = ctx.map.location(AnyEntity::Value(*alias)).unwrap(); 1975 return err!(loc, "alias cycle involving {}", alias); 1976 } 1977 } 1978 1979 Ok(()) 1980 } 1981 1982 // Parse a basic block, add contents to `ctx`. 1983 // 1984 // extended-basic-block ::= * block-header { instruction } 1985 // block-header ::= Block(block) [block-params] [block-flags] ":" 1986 // block-flags ::= [Cold] 1987 // 1988 fn parse_basic_block(&mut self, ctx: &mut Context) -> ParseResult<()> { 1989 // Collect comments for the next block. 1990 self.start_gathering_comments(); 1991 1992 let block_num = self.match_block("expected block header")?; 1993 let block = ctx.add_block(block_num, self.loc)?; 1994 1995 if block_num.as_u32() >= MAX_BLOCKS_IN_A_FUNCTION { 1996 return Err(self.error("too many blocks")); 1997 } 1998 1999 if self.token() == Some(Token::LPar) { 2000 self.parse_block_params(ctx, block)?; 2001 } 2002 2003 if self.optional(Token::Cold) { 2004 ctx.set_cold_block(block); 2005 } 2006 2007 self.match_token(Token::Colon, "expected ':' after block parameters")?; 2008 2009 // Collect any trailing comments. 2010 self.token(); 2011 self.claim_gathered_comments(block); 2012 2013 // extended-basic-block ::= block-header * { instruction } 2014 while match self.token() { 2015 Some(Token::Value(_)) 2016 | Some(Token::Identifier(_)) 2017 | Some(Token::LBracket) 2018 | Some(Token::SourceLoc(_)) => true, 2019 _ => false, 2020 } { 2021 let srcloc = self.optional_srcloc()?; 2022 2023 // We need to parse instruction results here because they are shared 2024 // between the parsing of value aliases and the parsing of instructions. 2025 // 2026 // inst-results ::= Value(v) { "," Value(v) } 2027 let results = self.parse_inst_results(ctx)?; 2028 2029 for result in &results { 2030 while ctx.function.dfg.num_values() <= result.index() { 2031 ctx.function.dfg.make_invalid_value_for_parser(); 2032 } 2033 } 2034 2035 match self.token() { 2036 Some(Token::Arrow) => { 2037 self.consume(); 2038 self.parse_value_alias(&results, ctx)?; 2039 } 2040 Some(Token::Equal) => { 2041 self.consume(); 2042 self.parse_instruction(&results, srcloc, ctx, block)?; 2043 } 2044 _ if !results.is_empty() => return err!(self.loc, "expected -> or ="), 2045 _ => self.parse_instruction(&results, srcloc, ctx, block)?, 2046 } 2047 } 2048 2049 Ok(()) 2050 } 2051 2052 // Parse parenthesized list of block parameters. 2053 // 2054 // block-params ::= * "(" ( block-param { "," block-param } )? ")" 2055 fn parse_block_params(&mut self, ctx: &mut Context, block: Block) -> ParseResult<()> { 2056 // block-params ::= * "(" ( block-param { "," block-param } )? ")" 2057 self.match_token(Token::LPar, "expected '(' before block parameters")?; 2058 2059 // block-params ::= "(" * ")" 2060 if self.token() == Some(Token::RPar) { 2061 self.consume(); 2062 return Ok(()); 2063 } 2064 2065 // block-params ::= "(" * block-param { "," block-param } ")" 2066 self.parse_block_param(ctx, block)?; 2067 2068 // block-params ::= "(" block-param * { "," block-param } ")" 2069 while self.optional(Token::Comma) { 2070 // block-params ::= "(" block-param { "," * block-param } ")" 2071 self.parse_block_param(ctx, block)?; 2072 } 2073 2074 // block-params ::= "(" block-param { "," block-param } * ")" 2075 self.match_token(Token::RPar, "expected ')' after block parameters")?; 2076 2077 Ok(()) 2078 } 2079 2080 // Parse a single block parameter declaration, and append it to `block`. 2081 // 2082 // block-param ::= * Value(v) [ "!" fact ] ":" Type(t) arg-loc? 2083 // arg-loc ::= "[" value-location "]" 2084 // 2085 fn parse_block_param(&mut self, ctx: &mut Context, block: Block) -> ParseResult<()> { 2086 // block-param ::= * Value(v) [ "!" fact ] ":" Type(t) arg-loc? 2087 let v = self.match_value("block argument must be a value")?; 2088 let v_location = self.loc; 2089 // block-param ::= Value(v) * [ "!" fact ] ":" Type(t) arg-loc? 2090 let fact = if self.token() == Some(Token::Bang) { 2091 self.consume(); 2092 // block-param ::= Value(v) [ "!" * fact ] ":" Type(t) arg-loc? 2093 Some(self.parse_fact()?) 2094 } else { 2095 None 2096 }; 2097 self.match_token(Token::Colon, "expected ':' after block argument")?; 2098 // block-param ::= Value(v) [ "!" fact ] ":" * Type(t) arg-loc? 2099 2100 while ctx.function.dfg.num_values() <= v.index() { 2101 ctx.function.dfg.make_invalid_value_for_parser(); 2102 } 2103 2104 let t = self.match_type("expected block argument type")?; 2105 // Allocate the block argument. 2106 ctx.function.dfg.append_block_param_for_parser(block, t, v); 2107 ctx.map.def_value(v, v_location)?; 2108 ctx.function.dfg.facts[v] = fact; 2109 2110 Ok(()) 2111 } 2112 2113 // Parse a "fact" for proof-carrying code, attached to a value. 2114 // 2115 // fact ::= "range" "(" bit-width "," min-value "," max-value ")" 2116 // | "dynamic_range" "(" bit-width "," expr "," expr ")" 2117 // | "mem" "(" memory-type "," mt-offset "," mt-offset [ "," "nullable" ] ")" 2118 // | "dynamic_mem" "(" memory-type "," expr "," expr [ "," "nullable" ] ")" 2119 // | "conflict" 2120 // bit-width ::= uimm64 2121 // min-value ::= uimm64 2122 // max-value ::= uimm64 2123 // valid-range ::= uimm64 2124 // mt-offset ::= uimm64 2125 fn parse_fact(&mut self) -> ParseResult<Fact> { 2126 match self.token() { 2127 Some(Token::Identifier("range")) => { 2128 self.consume(); 2129 self.match_token(Token::LPar, "`range` fact needs an opening `(`")?; 2130 let bit_width: u64 = self 2131 .match_uimm64("expected a bit-width value for `range` fact")? 2132 .into(); 2133 self.match_token(Token::Comma, "expected a comma")?; 2134 let min: u64 = self 2135 .match_uimm64("expected a min value for `range` fact")? 2136 .into(); 2137 self.match_token(Token::Comma, "expected a comma")?; 2138 let max: u64 = self 2139 .match_uimm64("expected a max value for `range` fact")? 2140 .into(); 2141 self.match_token(Token::RPar, "`range` fact needs a closing `)`")?; 2142 let bit_width_max = match bit_width { 2143 x if x > 64 => { 2144 return Err(self.error("bitwidth must be <= 64 bits on a `range` fact")); 2145 } 2146 64 => u64::MAX, 2147 x => (1u64 << x) - 1, 2148 }; 2149 if min > max { 2150 return Err(self.error( 2151 "min value must be less than or equal to max value on a `range` fact", 2152 )); 2153 } 2154 if max > bit_width_max { 2155 return Err( 2156 self.error("max value is out of range for bitwidth on a `range` fact") 2157 ); 2158 } 2159 Ok(Fact::Range { 2160 bit_width: u16::try_from(bit_width).unwrap(), 2161 min: min.into(), 2162 max: max.into(), 2163 }) 2164 } 2165 Some(Token::Identifier("dynamic_range")) => { 2166 self.consume(); 2167 self.match_token(Token::LPar, "`dynamic_range` fact needs an opening `(`")?; 2168 let bit_width: u64 = self 2169 .match_uimm64("expected a bit-width value for `dynamic_range` fact")? 2170 .into(); 2171 self.match_token(Token::Comma, "expected a comma")?; 2172 let min = self.parse_expr()?; 2173 self.match_token(Token::Comma, "expected a comma")?; 2174 let max = self.parse_expr()?; 2175 self.match_token(Token::RPar, "`dynamic_range` fact needs a closing `)`")?; 2176 Ok(Fact::DynamicRange { 2177 bit_width: u16::try_from(bit_width).unwrap(), 2178 min, 2179 max, 2180 }) 2181 } 2182 Some(Token::Identifier("mem")) => { 2183 self.consume(); 2184 self.match_token(Token::LPar, "expected a `(`")?; 2185 let ty = self.match_mt("expected a memory type for `mem` fact")?; 2186 self.match_token( 2187 Token::Comma, 2188 "expected a comma after memory type in `mem` fact", 2189 )?; 2190 let min_offset: u64 = self 2191 .match_uimm64("expected a uimm64 minimum pointer offset for `mem` fact")? 2192 .into(); 2193 self.match_token(Token::Comma, "expected a comma after offset in `mem` fact")?; 2194 let max_offset: u64 = self 2195 .match_uimm64("expected a uimm64 maximum pointer offset for `mem` fact")? 2196 .into(); 2197 let nullable = if self.token() == Some(Token::Comma) { 2198 self.consume(); 2199 self.match_token( 2200 Token::Identifier("nullable"), 2201 "expected `nullable` in last optional field of `dynamic_mem`", 2202 )?; 2203 true 2204 } else { 2205 false 2206 }; 2207 self.match_token(Token::RPar, "expected a `)`")?; 2208 Ok(Fact::Mem { 2209 ty, 2210 min_offset, 2211 max_offset, 2212 nullable, 2213 }) 2214 } 2215 Some(Token::Identifier("dynamic_mem")) => { 2216 self.consume(); 2217 self.match_token(Token::LPar, "expected a `(`")?; 2218 let ty = self.match_mt("expected a memory type for `dynamic_mem` fact")?; 2219 self.match_token( 2220 Token::Comma, 2221 "expected a comma after memory type in `dynamic_mem` fact", 2222 )?; 2223 let min = self.parse_expr()?; 2224 self.match_token( 2225 Token::Comma, 2226 "expected a comma after offset in `dynamic_mem` fact", 2227 )?; 2228 let max = self.parse_expr()?; 2229 let nullable = if self.token() == Some(Token::Comma) { 2230 self.consume(); 2231 self.match_token( 2232 Token::Identifier("nullable"), 2233 "expected `nullable` in last optional field of `dynamic_mem`", 2234 )?; 2235 true 2236 } else { 2237 false 2238 }; 2239 self.match_token(Token::RPar, "expected a `)`")?; 2240 Ok(Fact::DynamicMem { 2241 ty, 2242 min, 2243 max, 2244 nullable, 2245 }) 2246 } 2247 Some(Token::Identifier("def")) => { 2248 self.consume(); 2249 self.match_token(Token::LPar, "expected a `(`")?; 2250 let value = self.match_value("expected a value number in `def` fact")?; 2251 self.match_token(Token::RPar, "expected a `)`")?; 2252 Ok(Fact::Def { value }) 2253 } 2254 Some(Token::Identifier("compare")) => { 2255 self.consume(); 2256 self.match_token(Token::LPar, "expected a `(`")?; 2257 let kind = self.match_enum("expected intcc condition code in `compare` fact")?; 2258 self.match_token( 2259 Token::Comma, 2260 "expected comma in `compare` fact after condition code", 2261 )?; 2262 let lhs = self.parse_expr()?; 2263 self.match_token(Token::Comma, "expected comma in `compare` fact after LHS")?; 2264 let rhs = self.parse_expr()?; 2265 self.match_token(Token::RPar, "expected a `)`")?; 2266 Ok(Fact::Compare { kind, lhs, rhs }) 2267 } 2268 Some(Token::Identifier("conflict")) => { 2269 self.consume(); 2270 Ok(Fact::Conflict) 2271 } 2272 _ => Err(self.error( 2273 "expected a `range`, 'dynamic_range', `mem`, `dynamic_mem`, `def`, `compare` or `conflict` fact", 2274 )), 2275 } 2276 } 2277 2278 // Parse a dynamic expression used in some kinds of PCC facts. 2279 // 2280 // expr ::= base-expr 2281 // | base-expr + uimm64 // but in-range for imm64 2282 // | base-expr - uimm64 // but in-range for imm64 2283 // | imm64 2284 fn parse_expr(&mut self) -> ParseResult<Expr> { 2285 if let Some(Token::Integer(_)) = self.token() { 2286 let offset: i64 = self 2287 .match_imm64("expected imm64 for dynamic expression")? 2288 .into(); 2289 Ok(Expr { 2290 base: BaseExpr::None, 2291 offset, 2292 }) 2293 } else { 2294 let base = self.parse_base_expr()?; 2295 match self.token() { 2296 Some(Token::Plus) => { 2297 self.consume(); 2298 let offset: u64 = self 2299 .match_uimm64( 2300 "expected uimm64 in imm64 range for offset in dynamic expression", 2301 )? 2302 .into(); 2303 let offset: i64 = i64::try_from(offset).map_err(|_| { 2304 self.error("integer offset in dynamic expression is out of range") 2305 })?; 2306 Ok(Expr { base, offset }) 2307 } 2308 Some(Token::Integer(x)) if x.starts_with("-") => { 2309 let offset: i64 = self 2310 .match_imm64("expected an imm64 range for offset in dynamic expression")? 2311 .into(); 2312 Ok(Expr { base, offset }) 2313 } 2314 _ => Ok(Expr { base, offset: 0 }), 2315 } 2316 } 2317 } 2318 2319 // Parse the base part of a dynamic expression, used in some PCC facts. 2320 // 2321 // base-expr ::= GlobalValue(base) 2322 // | Value(base) 2323 // | "max" 2324 // | (epsilon) 2325 fn parse_base_expr(&mut self) -> ParseResult<BaseExpr> { 2326 match self.token() { 2327 Some(Token::Identifier("max")) => { 2328 self.consume(); 2329 Ok(BaseExpr::Max) 2330 } 2331 Some(Token::GlobalValue(..)) => { 2332 let gv = self.match_gv("expected global value")?; 2333 Ok(BaseExpr::GlobalValue(gv)) 2334 } 2335 Some(Token::Value(..)) => { 2336 let value = self.match_value("expected value")?; 2337 Ok(BaseExpr::Value(value)) 2338 } 2339 _ => Ok(BaseExpr::None), 2340 } 2341 } 2342 2343 // Parse instruction results and return them. 2344 // 2345 // inst-results ::= Value(v) { "," Value(v) } 2346 // 2347 fn parse_inst_results(&mut self, ctx: &mut Context) -> ParseResult<SmallVec<[Value; 1]>> { 2348 // Result value numbers. 2349 let mut results = SmallVec::new(); 2350 2351 // instruction ::= * [inst-results "="] Opcode(opc) ["." Type] ... 2352 // inst-results ::= * Value(v) { "," Value(v) } 2353 if let Some(Token::Value(v)) = self.token() { 2354 self.consume(); 2355 2356 results.push(v); 2357 2358 let fact = if self.token() == Some(Token::Bang) { 2359 self.consume(); 2360 // block-param ::= Value(v) [ "!" * fact ] ":" Type(t) arg-loc? 2361 Some(self.parse_fact()?) 2362 } else { 2363 None 2364 }; 2365 ctx.function.dfg.facts[v] = fact; 2366 2367 // inst-results ::= Value(v) * { "," Value(v) } 2368 while self.optional(Token::Comma) { 2369 // inst-results ::= Value(v) { "," * Value(v) } 2370 let v = self.match_value("expected result value")?; 2371 results.push(v); 2372 2373 let fact = if self.token() == Some(Token::Bang) { 2374 self.consume(); 2375 // block-param ::= Value(v) [ "!" * fact ] ":" Type(t) arg-loc? 2376 Some(self.parse_fact()?) 2377 } else { 2378 None 2379 }; 2380 ctx.function.dfg.facts[v] = fact; 2381 } 2382 } 2383 2384 Ok(results) 2385 } 2386 2387 // Parse a value alias, and append it to `block`. 2388 // 2389 // value_alias ::= [inst-results] "->" Value(v) 2390 // 2391 fn parse_value_alias(&mut self, results: &[Value], ctx: &mut Context) -> ParseResult<()> { 2392 if results.len() != 1 { 2393 return err!(self.loc, "wrong number of aliases"); 2394 } 2395 let result = results[0]; 2396 let dest = self.match_value("expected value alias")?; 2397 2398 // Allow duplicate definitions of aliases, as long as they are identical. 2399 if ctx.map.contains_value(result) { 2400 if let Some(old) = ctx.function.dfg.value_alias_dest_for_serialization(result) { 2401 if old != dest { 2402 return err!( 2403 self.loc, 2404 "value {} is already defined as an alias with destination {}", 2405 result, 2406 old 2407 ); 2408 } 2409 } else { 2410 return err!(self.loc, "value {} is already defined"); 2411 } 2412 } else { 2413 ctx.map.def_value(result, self.loc)?; 2414 } 2415 2416 if !ctx.map.contains_value(dest) { 2417 return err!(self.loc, "value {} is not yet defined", dest); 2418 } 2419 2420 ctx.function 2421 .dfg 2422 .make_value_alias_for_serialization(dest, result); 2423 2424 ctx.aliases.push(result); 2425 Ok(()) 2426 } 2427 2428 // Parse an instruction, append it to `block`. 2429 // 2430 // instruction ::= [inst-results "="] Opcode(opc) ["." Type] ... 2431 // 2432 fn parse_instruction( 2433 &mut self, 2434 results: &[Value], 2435 srcloc: ir::SourceLoc, 2436 ctx: &mut Context, 2437 block: Block, 2438 ) -> ParseResult<()> { 2439 // Define the result values. 2440 for val in results { 2441 ctx.map.def_value(*val, self.loc)?; 2442 } 2443 2444 // Collect comments for the next instruction. 2445 self.start_gathering_comments(); 2446 2447 // instruction ::= [inst-results "="] * Opcode(opc) ["." Type] ... 2448 let opcode = if let Some(Token::Identifier(text)) = self.token() { 2449 match text.parse() { 2450 Ok(opc) => opc, 2451 Err(msg) => return err!(self.loc, "{}: '{}'", msg, text), 2452 } 2453 } else { 2454 return err!(self.loc, "expected instruction opcode"); 2455 }; 2456 let opcode_loc = self.loc; 2457 self.consume(); 2458 2459 // Look for a controlling type variable annotation. 2460 // instruction ::= [inst-results "="] Opcode(opc) * ["." Type] ... 2461 let explicit_ctrl_type = if self.optional(Token::Dot) { 2462 if let Some(Token::Type(_t)) = self.token() { 2463 Some(self.match_type("expected type after 'opcode.'")?) 2464 } else { 2465 let dt = self.match_dt("expected dynamic type")?; 2466 self.concrete_from_dt(dt, ctx) 2467 } 2468 } else { 2469 None 2470 }; 2471 2472 // instruction ::= [inst-results "="] Opcode(opc) ["." Type] * ... 2473 let inst_data = self.parse_inst_operands(ctx, opcode, explicit_ctrl_type)?; 2474 2475 // We're done parsing the instruction data itself. 2476 // 2477 // We still need to check that the number of result values in the source 2478 // matches the opcode or function call signature. We also need to create 2479 // values with the right type for all the instruction results and parse 2480 // and attach stack map entries, if present. 2481 let ctrl_typevar = self.infer_typevar(ctx, opcode, explicit_ctrl_type, &inst_data)?; 2482 let inst = ctx.function.dfg.make_inst(inst_data); 2483 if opcode.is_call() && !opcode.is_return() && self.optional(Token::Comma) { 2484 self.match_identifier("stack_map", "expected `stack_map = [...]`")?; 2485 self.match_token(Token::Equal, "expected `= [...]`")?; 2486 self.match_token(Token::LBracket, "expected `[...]`")?; 2487 while !self.optional(Token::RBracket) { 2488 let ty = self.match_type("expected `<type> @ <slot> + <offset>`")?; 2489 self.match_token(Token::At, "expected `@ <slot> + <offset>`")?; 2490 let slot = self.match_ss("expected `<slot> + <offset>`")?; 2491 let offset: u32 = match self.token() { 2492 Some(Token::Integer(s)) if s.starts_with('+') => { 2493 self.match_uimm32("expected a u32 offset")?.into() 2494 } 2495 _ => { 2496 self.match_token(Token::Plus, "expected `+ <offset>`")?; 2497 self.match_uimm32("expected a u32 offset")?.into() 2498 } 2499 }; 2500 ctx.function 2501 .dfg 2502 .append_user_stack_map_entry(inst, ir::UserStackMapEntry { ty, slot, offset }); 2503 if !self.optional(Token::Comma) { 2504 self.match_token(Token::RBracket, "expected `,` or `]`")?; 2505 break; 2506 } 2507 } 2508 } 2509 let num_results = 2510 ctx.function 2511 .dfg 2512 .make_inst_results_for_parser(inst, ctrl_typevar, results); 2513 ctx.function.layout.append_inst(inst, block); 2514 ctx.map 2515 .def_entity(inst.into(), opcode_loc) 2516 .expect("duplicate inst references created"); 2517 2518 if !srcloc.is_default() { 2519 ctx.function.set_srcloc(inst, srcloc); 2520 } 2521 2522 if results.len() != num_results { 2523 return err!( 2524 self.loc, 2525 "instruction produces {} result values, {} given", 2526 num_results, 2527 results.len() 2528 ); 2529 } 2530 2531 // Collect any trailing comments. 2532 self.token(); 2533 self.claim_gathered_comments(inst); 2534 2535 Ok(()) 2536 } 2537 2538 // Type inference for polymorphic instructions. 2539 // 2540 // The controlling type variable can be specified explicitly as 'splat.i32x4 v5', or it can be 2541 // inferred from `inst_data.typevar_operand` for some opcodes. 2542 // 2543 // Returns the controlling typevar for a polymorphic opcode, or `INVALID` for a non-polymorphic 2544 // opcode. 2545 fn infer_typevar( 2546 &self, 2547 ctx: &Context, 2548 opcode: Opcode, 2549 explicit_ctrl_type: Option<Type>, 2550 inst_data: &InstructionData, 2551 ) -> ParseResult<Type> { 2552 let constraints = opcode.constraints(); 2553 let ctrl_type = match explicit_ctrl_type { 2554 Some(t) => t, 2555 None => { 2556 if constraints.use_typevar_operand() { 2557 // This is an opcode that supports type inference, AND there was no 2558 // explicit type specified. Look up `ctrl_value` to see if it was defined 2559 // already. 2560 // TBD: If it is defined in another block, the type should have been 2561 // specified explicitly. It is unfortunate that the correctness of IR 2562 // depends on the layout of the blocks. 2563 let ctrl_src_value = inst_data 2564 .typevar_operand(&ctx.function.dfg.value_lists) 2565 .expect("Constraints <-> Format inconsistency"); 2566 if !ctx.map.contains_value(ctrl_src_value) { 2567 return err!( 2568 self.loc, 2569 "type variable required for polymorphic opcode, e.g. '{}.{}'; \ 2570 can't infer from {} which is not yet defined", 2571 opcode, 2572 constraints.ctrl_typeset().unwrap().example(), 2573 ctrl_src_value 2574 ); 2575 } 2576 if !ctx.function.dfg.value_is_valid_for_parser(ctrl_src_value) { 2577 return err!( 2578 self.loc, 2579 "type variable required for polymorphic opcode, e.g. '{}.{}'; \ 2580 can't infer from {} which is not yet resolved", 2581 opcode, 2582 constraints.ctrl_typeset().unwrap().example(), 2583 ctrl_src_value 2584 ); 2585 } 2586 ctx.function.dfg.value_type(ctrl_src_value) 2587 } else if constraints.is_polymorphic() { 2588 // This opcode does not support type inference, so the explicit type 2589 // variable is required. 2590 return err!( 2591 self.loc, 2592 "type variable required for polymorphic opcode, e.g. '{}.{}'", 2593 opcode, 2594 constraints.ctrl_typeset().unwrap().example() 2595 ); 2596 } else { 2597 // This is a non-polymorphic opcode. No typevar needed. 2598 INVALID 2599 } 2600 } 2601 }; 2602 2603 // Verify that `ctrl_type` is valid for the controlling type variable. We don't want to 2604 // attempt deriving types from an incorrect basis. 2605 // This is not a complete type check. The verifier does that. 2606 if let Some(typeset) = constraints.ctrl_typeset() { 2607 // This is a polymorphic opcode. 2608 if !typeset.contains(ctrl_type) { 2609 return err!( 2610 self.loc, 2611 "{} is not a valid typevar for {}", 2612 ctrl_type, 2613 opcode 2614 ); 2615 } 2616 // Treat it as a syntax error to specify a typevar on a non-polymorphic opcode. 2617 } else if ctrl_type != INVALID { 2618 return err!(self.loc, "{} does not take a typevar", opcode); 2619 } 2620 2621 Ok(ctrl_type) 2622 } 2623 2624 // Parse comma-separated value list into a VariableArgs struct. 2625 // 2626 // value_list ::= [ value { "," value } ] 2627 // 2628 fn parse_value_list(&mut self) -> ParseResult<VariableArgs> { 2629 let mut args = VariableArgs::new(); 2630 2631 if let Some(Token::Value(v)) = self.token() { 2632 args.push(v); 2633 self.consume(); 2634 } else { 2635 return Ok(args); 2636 } 2637 2638 while self.optional(Token::Comma) { 2639 args.push(self.match_value("expected value in argument list")?); 2640 } 2641 2642 Ok(args) 2643 } 2644 2645 // Parse an optional value list enclosed in parentheses. 2646 fn parse_opt_value_list(&mut self) -> ParseResult<VariableArgs> { 2647 if !self.optional(Token::LPar) { 2648 return Ok(VariableArgs::new()); 2649 } 2650 2651 let args = self.parse_value_list()?; 2652 2653 self.match_token(Token::RPar, "expected ')' after arguments")?; 2654 2655 Ok(args) 2656 } 2657 2658 /// Parse a CLIF run command. 2659 /// 2660 /// run-command ::= "run" [":" invocation comparison expected] 2661 /// \ "print" [":" invocation] 2662 fn parse_run_command(&mut self, sig: &Signature) -> ParseResult<RunCommand> { 2663 // skip semicolon 2664 match self.token() { 2665 Some(Token::Identifier("run")) => { 2666 self.consume(); 2667 if self.optional(Token::Colon) { 2668 let invocation = self.parse_run_invocation(sig)?; 2669 let comparison = self.parse_run_comparison()?; 2670 let expected = self.parse_run_returns(sig)?; 2671 Ok(RunCommand::Run(invocation, comparison, expected)) 2672 } else if sig.params.is_empty() 2673 && sig.returns.len() == 1 2674 && sig.returns[0].value_type.is_int() 2675 { 2676 // To match the existing run behavior that does not require an explicit 2677 // invocation, we create an invocation from a function like `() -> i*` and 2678 // require the result to be non-zero. 2679 let invocation = Invocation::new("default", vec![]); 2680 let expected = vec![DataValue::I8(0)]; 2681 let comparison = Comparison::NotEquals; 2682 Ok(RunCommand::Run(invocation, comparison, expected)) 2683 } else { 2684 Err(self.error("unable to parse the run command")) 2685 } 2686 } 2687 Some(Token::Identifier("print")) => { 2688 self.consume(); 2689 if self.optional(Token::Colon) { 2690 Ok(RunCommand::Print(self.parse_run_invocation(sig)?)) 2691 } else if sig.params.is_empty() { 2692 // To allow printing of functions like `() -> *`, we create a no-arg invocation. 2693 let invocation = Invocation::new("default", vec![]); 2694 Ok(RunCommand::Print(invocation)) 2695 } else { 2696 Err(self.error("unable to parse the print command")) 2697 } 2698 } 2699 _ => Err(self.error("expected a 'run:' or 'print:' command")), 2700 } 2701 } 2702 2703 /// Parse the invocation of a CLIF function. 2704 /// 2705 /// This is different from parsing a CLIF `call`; it is used in parsing run commands like 2706 /// `run: %fn(42, 4.2) == false`. 2707 /// 2708 /// invocation ::= name "(" [data-value-list] ")" 2709 fn parse_run_invocation(&mut self, sig: &Signature) -> ParseResult<Invocation> { 2710 if let Some(Token::Name(name)) = self.token() { 2711 self.consume(); 2712 self.match_token( 2713 Token::LPar, 2714 "expected invocation parentheses, e.g. %fn(...)", 2715 )?; 2716 2717 let arg_types = sig 2718 .params 2719 .iter() 2720 .map(|abi| abi.value_type) 2721 .collect::<Vec<_>>(); 2722 let args = self.parse_data_value_list(&arg_types)?; 2723 2724 self.match_token( 2725 Token::RPar, 2726 "expected invocation parentheses, e.g. %fn(...)", 2727 )?; 2728 Ok(Invocation::new(name, args)) 2729 } else { 2730 Err(self.error("expected a function name, e.g. %my_fn")) 2731 } 2732 } 2733 2734 /// Parse a comparison operator for run commands. 2735 /// 2736 /// comparison ::= "==" | "!=" 2737 fn parse_run_comparison(&mut self) -> ParseResult<Comparison> { 2738 if self.optional(Token::Equal) { 2739 self.match_token(Token::Equal, "expected another =")?; 2740 Ok(Comparison::Equals) 2741 } else if self.optional(Token::Bang) { 2742 self.match_token(Token::Equal, "expected a =")?; 2743 Ok(Comparison::NotEquals) 2744 } else { 2745 Err(self.error("unable to parse a valid comparison operator")) 2746 } 2747 } 2748 2749 /// Parse the expected return values of a run invocation. 2750 /// 2751 /// expected ::= "[" "]" 2752 /// | data-value 2753 /// | "[" data-value-list "]" 2754 fn parse_run_returns(&mut self, sig: &Signature) -> ParseResult<Vec<DataValue>> { 2755 if sig.returns.len() != 1 { 2756 self.match_token(Token::LBracket, "expected a left bracket [")?; 2757 } 2758 2759 let returns = self 2760 .parse_data_value_list(&sig.returns.iter().map(|a| a.value_type).collect::<Vec<_>>())?; 2761 2762 if sig.returns.len() != 1 { 2763 self.match_token(Token::RBracket, "expected a right bracket ]")?; 2764 } 2765 Ok(returns) 2766 } 2767 2768 /// Parse a comma-separated list of data values. 2769 /// 2770 /// data-value-list ::= [data-value {"," data-value-list}] 2771 fn parse_data_value_list(&mut self, types: &[Type]) -> ParseResult<Vec<DataValue>> { 2772 let mut values = vec![]; 2773 for ty in types.iter().take(1) { 2774 values.push(self.parse_data_value(*ty)?); 2775 } 2776 for ty in types.iter().skip(1) { 2777 self.match_token( 2778 Token::Comma, 2779 "expected a comma between invocation arguments", 2780 )?; 2781 values.push(self.parse_data_value(*ty)?); 2782 } 2783 Ok(values) 2784 } 2785 2786 /// Parse a data value; e.g. `42`, `4.2`, `true`. 2787 /// 2788 /// data-value-list ::= [data-value {"," data-value-list}] 2789 fn parse_data_value(&mut self, ty: Type) -> ParseResult<DataValue> { 2790 let dv = match ty { 2791 I8 => DataValue::from(self.match_imm8("expected a i8")?), 2792 I16 => DataValue::from(self.match_imm16("expected an i16")?), 2793 I32 => DataValue::from(self.match_imm32("expected an i32")?), 2794 I64 => DataValue::from(Into::<i64>::into(self.match_imm64("expected an i64")?)), 2795 I128 => DataValue::from(self.match_imm128("expected an i128")?), 2796 F32 => DataValue::from(self.match_ieee32("expected an f32")?), 2797 F64 => DataValue::from(self.match_ieee64("expected an f64")?), 2798 _ if (ty.is_vector() || ty.is_dynamic_vector()) => { 2799 let as_vec = self.match_uimm128(ty)?.into_vec(); 2800 if as_vec.len() == 16 { 2801 let mut as_array = [0; 16]; 2802 as_array.copy_from_slice(&as_vec[..]); 2803 DataValue::from(as_array) 2804 } else if as_vec.len() == 8 { 2805 let mut as_array = [0; 8]; 2806 as_array.copy_from_slice(&as_vec[..]); 2807 DataValue::from(as_array) 2808 } else { 2809 return Err(self.error("only 128-bit vectors are currently supported")); 2810 } 2811 } 2812 _ => return Err(self.error(&format!("don't know how to parse data values of: {}", ty))), 2813 }; 2814 Ok(dv) 2815 } 2816 2817 // Parse the operands following the instruction opcode. 2818 // This depends on the format of the opcode. 2819 fn parse_inst_operands( 2820 &mut self, 2821 ctx: &mut Context, 2822 opcode: Opcode, 2823 explicit_control_type: Option<Type>, 2824 ) -> ParseResult<InstructionData> { 2825 let idata = match opcode.format() { 2826 InstructionFormat::Unary => InstructionData::Unary { 2827 opcode, 2828 arg: self.match_value("expected SSA value operand")?, 2829 }, 2830 InstructionFormat::UnaryImm => { 2831 let msg = |bits| format!("expected immediate {bits}-bit integer operand"); 2832 let unsigned = match explicit_control_type { 2833 Some(types::I8) => self.match_imm8(&msg(8))? as u8 as i64, 2834 Some(types::I16) => self.match_imm16(&msg(16))? as u16 as i64, 2835 Some(types::I32) => self.match_imm32(&msg(32))? as u32 as i64, 2836 Some(types::I64) => self.match_imm64(&msg(64))?.bits(), 2837 _ => { 2838 return err!( 2839 self.loc, 2840 "expected one of the following type: i8, i16, i32 or i64" 2841 ) 2842 } 2843 }; 2844 InstructionData::UnaryImm { 2845 opcode, 2846 imm: Imm64::new(unsigned), 2847 } 2848 } 2849 InstructionFormat::UnaryIeee32 => InstructionData::UnaryIeee32 { 2850 opcode, 2851 imm: self.match_ieee32("expected immediate 32-bit float operand")?, 2852 }, 2853 InstructionFormat::UnaryIeee64 => InstructionData::UnaryIeee64 { 2854 opcode, 2855 imm: self.match_ieee64("expected immediate 64-bit float operand")?, 2856 }, 2857 InstructionFormat::UnaryConst => { 2858 let constant_handle = if let Some(Token::Constant(_)) = self.token() { 2859 // If handed a `const?`, use that. 2860 let c = self.match_constant()?; 2861 ctx.check_constant(c, self.loc)?; 2862 c 2863 } else if let Some(controlling_type) = explicit_control_type { 2864 // If an explicit control type is present, we expect a sized value and insert 2865 // it in the constant pool. 2866 let uimm128 = self.match_uimm128(controlling_type)?; 2867 ctx.function.dfg.constants.insert(uimm128) 2868 } else { 2869 return err!( 2870 self.loc, 2871 "Expected either a const entity or a typed value, e.g. inst.i32x4 [...]" 2872 ); 2873 }; 2874 InstructionData::UnaryConst { 2875 opcode, 2876 constant_handle, 2877 } 2878 } 2879 InstructionFormat::UnaryGlobalValue => { 2880 let gv = self.match_gv("expected global value")?; 2881 ctx.check_gv(gv, self.loc)?; 2882 InstructionData::UnaryGlobalValue { 2883 opcode, 2884 global_value: gv, 2885 } 2886 } 2887 InstructionFormat::Binary => { 2888 let lhs = self.match_value("expected SSA value first operand")?; 2889 self.match_token(Token::Comma, "expected ',' between operands")?; 2890 let rhs = self.match_value("expected SSA value second operand")?; 2891 InstructionData::Binary { 2892 opcode, 2893 args: [lhs, rhs], 2894 } 2895 } 2896 InstructionFormat::BinaryImm8 => { 2897 let arg = self.match_value("expected SSA value first operand")?; 2898 self.match_token(Token::Comma, "expected ',' between operands")?; 2899 let imm = self.match_uimm8("expected unsigned 8-bit immediate")?; 2900 InstructionData::BinaryImm8 { opcode, arg, imm } 2901 } 2902 InstructionFormat::BinaryImm64 => { 2903 let lhs = self.match_value("expected SSA value first operand")?; 2904 self.match_token(Token::Comma, "expected ',' between operands")?; 2905 let rhs = self.match_imm64("expected immediate integer second operand")?; 2906 InstructionData::BinaryImm64 { 2907 opcode, 2908 arg: lhs, 2909 imm: rhs, 2910 } 2911 } 2912 InstructionFormat::Ternary => { 2913 // Names here refer to the `select` instruction. 2914 // This format is also use by `fma`. 2915 let ctrl_arg = self.match_value("expected SSA value control operand")?; 2916 self.match_token(Token::Comma, "expected ',' between operands")?; 2917 let true_arg = self.match_value("expected SSA value true operand")?; 2918 self.match_token(Token::Comma, "expected ',' between operands")?; 2919 let false_arg = self.match_value("expected SSA value false operand")?; 2920 InstructionData::Ternary { 2921 opcode, 2922 args: [ctrl_arg, true_arg, false_arg], 2923 } 2924 } 2925 InstructionFormat::MultiAry => { 2926 let args = self.parse_value_list()?; 2927 InstructionData::MultiAry { 2928 opcode, 2929 args: args.into_value_list(&[], &mut ctx.function.dfg.value_lists), 2930 } 2931 } 2932 InstructionFormat::NullAry => InstructionData::NullAry { opcode }, 2933 InstructionFormat::Jump => { 2934 // Parse the destination block number. 2935 let block_num = self.match_block("expected jump destination block")?; 2936 let args = self.parse_opt_value_list()?; 2937 let destination = ctx.function.dfg.block_call(block_num, &args); 2938 InstructionData::Jump { 2939 opcode, 2940 destination, 2941 } 2942 } 2943 InstructionFormat::Brif => { 2944 let arg = self.match_value("expected SSA value control operand")?; 2945 self.match_token(Token::Comma, "expected ',' between operands")?; 2946 let block_then = { 2947 let block_num = self.match_block("expected branch then block")?; 2948 let args = self.parse_opt_value_list()?; 2949 ctx.function.dfg.block_call(block_num, &args) 2950 }; 2951 self.match_token(Token::Comma, "expected ',' between operands")?; 2952 let block_else = { 2953 let block_num = self.match_block("expected branch else block")?; 2954 let args = self.parse_opt_value_list()?; 2955 ctx.function.dfg.block_call(block_num, &args) 2956 }; 2957 InstructionData::Brif { 2958 opcode, 2959 arg, 2960 blocks: [block_then, block_else], 2961 } 2962 } 2963 InstructionFormat::BranchTable => { 2964 let arg = self.match_value("expected SSA value operand")?; 2965 self.match_token(Token::Comma, "expected ',' between operands")?; 2966 let block_num = self.match_block("expected branch destination block")?; 2967 let args = self.parse_opt_value_list()?; 2968 let destination = ctx.function.dfg.block_call(block_num, &args); 2969 self.match_token(Token::Comma, "expected ',' between operands")?; 2970 let table = self.parse_jump_table(ctx, destination)?; 2971 InstructionData::BranchTable { opcode, arg, table } 2972 } 2973 InstructionFormat::TernaryImm8 => { 2974 let lhs = self.match_value("expected SSA value first operand")?; 2975 self.match_token(Token::Comma, "expected ',' between operands")?; 2976 let rhs = self.match_value("expected SSA value last operand")?; 2977 self.match_token(Token::Comma, "expected ',' between operands")?; 2978 let imm = self.match_uimm8("expected 8-bit immediate")?; 2979 InstructionData::TernaryImm8 { 2980 opcode, 2981 imm, 2982 args: [lhs, rhs], 2983 } 2984 } 2985 InstructionFormat::Shuffle => { 2986 let a = self.match_value("expected SSA value first operand")?; 2987 self.match_token(Token::Comma, "expected ',' between operands")?; 2988 let b = self.match_value("expected SSA value second operand")?; 2989 self.match_token(Token::Comma, "expected ',' between operands")?; 2990 let uimm128 = self.match_uimm128(I8X16)?; 2991 let imm = ctx.function.dfg.immediates.push(uimm128); 2992 InstructionData::Shuffle { 2993 opcode, 2994 imm, 2995 args: [a, b], 2996 } 2997 } 2998 InstructionFormat::IntCompare => { 2999 let cond = self.match_enum("expected intcc condition code")?; 3000 let lhs = self.match_value("expected SSA value first operand")?; 3001 self.match_token(Token::Comma, "expected ',' between operands")?; 3002 let rhs = self.match_value("expected SSA value second operand")?; 3003 InstructionData::IntCompare { 3004 opcode, 3005 cond, 3006 args: [lhs, rhs], 3007 } 3008 } 3009 InstructionFormat::IntCompareImm => { 3010 let cond = self.match_enum("expected intcc condition code")?; 3011 let lhs = self.match_value("expected SSA value first operand")?; 3012 self.match_token(Token::Comma, "expected ',' between operands")?; 3013 let rhs = self.match_imm64("expected immediate second operand")?; 3014 InstructionData::IntCompareImm { 3015 opcode, 3016 cond, 3017 arg: lhs, 3018 imm: rhs, 3019 } 3020 } 3021 InstructionFormat::FloatCompare => { 3022 let cond = self.match_enum("expected floatcc condition code")?; 3023 let lhs = self.match_value("expected SSA value first operand")?; 3024 self.match_token(Token::Comma, "expected ',' between operands")?; 3025 let rhs = self.match_value("expected SSA value second operand")?; 3026 InstructionData::FloatCompare { 3027 opcode, 3028 cond, 3029 args: [lhs, rhs], 3030 } 3031 } 3032 InstructionFormat::Call => { 3033 let func_ref = self.match_fn("expected function reference")?; 3034 ctx.check_fn(func_ref, self.loc)?; 3035 self.match_token(Token::LPar, "expected '(' before arguments")?; 3036 let args = self.parse_value_list()?; 3037 self.match_token(Token::RPar, "expected ')' after arguments")?; 3038 InstructionData::Call { 3039 opcode, 3040 func_ref, 3041 args: args.into_value_list(&[], &mut ctx.function.dfg.value_lists), 3042 } 3043 } 3044 InstructionFormat::CallIndirect => { 3045 let sig_ref = self.match_sig("expected signature reference")?; 3046 ctx.check_sig(sig_ref, self.loc)?; 3047 self.match_token(Token::Comma, "expected ',' between operands")?; 3048 let callee = self.match_value("expected SSA value callee operand")?; 3049 self.match_token(Token::LPar, "expected '(' before arguments")?; 3050 let args = self.parse_value_list()?; 3051 self.match_token(Token::RPar, "expected ')' after arguments")?; 3052 InstructionData::CallIndirect { 3053 opcode, 3054 sig_ref, 3055 args: args.into_value_list(&[callee], &mut ctx.function.dfg.value_lists), 3056 } 3057 } 3058 InstructionFormat::FuncAddr => { 3059 let func_ref = self.match_fn("expected function reference")?; 3060 ctx.check_fn(func_ref, self.loc)?; 3061 InstructionData::FuncAddr { opcode, func_ref } 3062 } 3063 InstructionFormat::StackLoad => { 3064 let ss = self.match_ss("expected stack slot number: ss«n»")?; 3065 ctx.check_ss(ss, self.loc)?; 3066 let offset = self.optional_offset32()?; 3067 InstructionData::StackLoad { 3068 opcode, 3069 stack_slot: ss, 3070 offset, 3071 } 3072 } 3073 InstructionFormat::StackStore => { 3074 let arg = self.match_value("expected SSA value operand")?; 3075 self.match_token(Token::Comma, "expected ',' between operands")?; 3076 let ss = self.match_ss("expected stack slot number: ss«n»")?; 3077 ctx.check_ss(ss, self.loc)?; 3078 let offset = self.optional_offset32()?; 3079 InstructionData::StackStore { 3080 opcode, 3081 arg, 3082 stack_slot: ss, 3083 offset, 3084 } 3085 } 3086 InstructionFormat::DynamicStackLoad => { 3087 let dss = self.match_dss("expected dynamic stack slot number: dss«n»")?; 3088 ctx.check_dss(dss, self.loc)?; 3089 InstructionData::DynamicStackLoad { 3090 opcode, 3091 dynamic_stack_slot: dss, 3092 } 3093 } 3094 InstructionFormat::DynamicStackStore => { 3095 let arg = self.match_value("expected SSA value operand")?; 3096 self.match_token(Token::Comma, "expected ',' between operands")?; 3097 let dss = self.match_dss("expected dynamic stack slot number: dss«n»")?; 3098 ctx.check_dss(dss, self.loc)?; 3099 InstructionData::DynamicStackStore { 3100 opcode, 3101 arg, 3102 dynamic_stack_slot: dss, 3103 } 3104 } 3105 InstructionFormat::Load => { 3106 let flags = self.optional_memflags()?; 3107 let addr = self.match_value("expected SSA value address")?; 3108 let offset = self.optional_offset32()?; 3109 InstructionData::Load { 3110 opcode, 3111 flags, 3112 arg: addr, 3113 offset, 3114 } 3115 } 3116 InstructionFormat::Store => { 3117 let flags = self.optional_memflags()?; 3118 let arg = self.match_value("expected SSA value operand")?; 3119 self.match_token(Token::Comma, "expected ',' between operands")?; 3120 let addr = self.match_value("expected SSA value address")?; 3121 let offset = self.optional_offset32()?; 3122 InstructionData::Store { 3123 opcode, 3124 flags, 3125 args: [arg, addr], 3126 offset, 3127 } 3128 } 3129 InstructionFormat::Trap => { 3130 let code = self.match_enum("expected trap code")?; 3131 InstructionData::Trap { opcode, code } 3132 } 3133 InstructionFormat::CondTrap => { 3134 let arg = self.match_value("expected SSA value operand")?; 3135 self.match_token(Token::Comma, "expected ',' between operands")?; 3136 let code = self.match_enum("expected trap code")?; 3137 InstructionData::CondTrap { opcode, arg, code } 3138 } 3139 InstructionFormat::AtomicCas => { 3140 let flags = self.optional_memflags()?; 3141 let addr = self.match_value("expected SSA value address")?; 3142 self.match_token(Token::Comma, "expected ',' between operands")?; 3143 let expected = self.match_value("expected SSA value address")?; 3144 self.match_token(Token::Comma, "expected ',' between operands")?; 3145 let replacement = self.match_value("expected SSA value address")?; 3146 InstructionData::AtomicCas { 3147 opcode, 3148 flags, 3149 args: [addr, expected, replacement], 3150 } 3151 } 3152 InstructionFormat::AtomicRmw => { 3153 let flags = self.optional_memflags()?; 3154 let op = self.match_enum("expected AtomicRmwOp")?; 3155 let addr = self.match_value("expected SSA value address")?; 3156 self.match_token(Token::Comma, "expected ',' between operands")?; 3157 let arg2 = self.match_value("expected SSA value address")?; 3158 InstructionData::AtomicRmw { 3159 opcode, 3160 flags, 3161 op, 3162 args: [addr, arg2], 3163 } 3164 } 3165 InstructionFormat::LoadNoOffset => { 3166 let flags = self.optional_memflags()?; 3167 let addr = self.match_value("expected SSA value address")?; 3168 InstructionData::LoadNoOffset { 3169 opcode, 3170 flags, 3171 arg: addr, 3172 } 3173 } 3174 InstructionFormat::StoreNoOffset => { 3175 let flags = self.optional_memflags()?; 3176 let arg = self.match_value("expected SSA value operand")?; 3177 self.match_token(Token::Comma, "expected ',' between operands")?; 3178 let addr = self.match_value("expected SSA value address")?; 3179 InstructionData::StoreNoOffset { 3180 opcode, 3181 flags, 3182 args: [arg, addr], 3183 } 3184 } 3185 InstructionFormat::IntAddTrap => { 3186 let a = self.match_value("expected SSA value operand")?; 3187 self.match_token(Token::Comma, "expected ',' between operands")?; 3188 let b = self.match_value("expected SSA value operand")?; 3189 self.match_token(Token::Comma, "expected ',' between operands")?; 3190 let code = self.match_enum("expected trap code")?; 3191 InstructionData::IntAddTrap { 3192 opcode, 3193 args: [a, b], 3194 code, 3195 } 3196 } 3197 }; 3198 Ok(idata) 3199 } 3200 } 3201 3202 #[cfg(test)] 3203 mod tests { 3204 use super::*; 3205 use crate::isaspec::IsaSpec; 3206 3207 #[test] 3208 fn argument_type() { 3209 let mut p = Parser::new("i32 sext"); 3210 let arg = p.parse_abi_param().unwrap(); 3211 assert_eq!(arg.value_type, types::I32); 3212 assert_eq!(arg.extension, ArgumentExtension::Sext); 3213 assert_eq!(arg.purpose, ArgumentPurpose::Normal); 3214 let ParseError { 3215 location, 3216 message, 3217 is_warning, 3218 } = p.parse_abi_param().unwrap_err(); 3219 assert_eq!(location.line_number, 1); 3220 assert_eq!(message, "expected parameter type"); 3221 assert!(!is_warning); 3222 } 3223 3224 #[test] 3225 fn aliases() { 3226 let (func, details) = Parser::new( 3227 "function %qux() system_v { 3228 block0: 3229 v4 = iconst.i8 6 3230 v3 -> v4 3231 v1 = iadd_imm v3, 17 3232 }", 3233 ) 3234 .parse_function() 3235 .unwrap(); 3236 assert_eq!(func.name.to_string(), "%qux"); 3237 let v4 = details.map.lookup_str("v4").unwrap(); 3238 assert_eq!(v4.to_string(), "v4"); 3239 let v3 = details.map.lookup_str("v3").unwrap(); 3240 assert_eq!(v3.to_string(), "v3"); 3241 match v3 { 3242 AnyEntity::Value(v3) => { 3243 let aliased_to = func.dfg.resolve_aliases(v3); 3244 assert_eq!(aliased_to.to_string(), "v4"); 3245 } 3246 _ => panic!("expected value: {}", v3), 3247 } 3248 } 3249 3250 #[test] 3251 fn signature() { 3252 let sig = Parser::new("()system_v").parse_signature().unwrap(); 3253 assert_eq!(sig.params.len(), 0); 3254 assert_eq!(sig.returns.len(), 0); 3255 assert_eq!(sig.call_conv, CallConv::SystemV); 3256 3257 let sig2 = Parser::new("(i8 uext, f32, f64, i32 sret) -> i32 sext, f64 system_v") 3258 .parse_signature() 3259 .unwrap(); 3260 assert_eq!( 3261 sig2.to_string(), 3262 "(i8 uext, f32, f64, i32 sret) -> i32 sext, f64 system_v" 3263 ); 3264 assert_eq!(sig2.call_conv, CallConv::SystemV); 3265 3266 // Old-style signature without a calling convention. 3267 assert_eq!( 3268 Parser::new("()").parse_signature().unwrap().to_string(), 3269 "() fast" 3270 ); 3271 assert_eq!( 3272 Parser::new("() notacc") 3273 .parse_signature() 3274 .unwrap_err() 3275 .to_string(), 3276 "1: unknown calling convention: notacc" 3277 ); 3278 3279 // `void` is not recognized as a type by the lexer. It should not appear in files. 3280 assert_eq!( 3281 Parser::new("() -> void") 3282 .parse_signature() 3283 .unwrap_err() 3284 .to_string(), 3285 "1: expected parameter type" 3286 ); 3287 assert_eq!( 3288 Parser::new("i8 -> i8") 3289 .parse_signature() 3290 .unwrap_err() 3291 .to_string(), 3292 "1: expected function signature: ( args... )" 3293 ); 3294 assert_eq!( 3295 Parser::new("(i8 -> i8") 3296 .parse_signature() 3297 .unwrap_err() 3298 .to_string(), 3299 "1: expected ')' after function arguments" 3300 ); 3301 } 3302 3303 #[test] 3304 fn stack_slot_decl() { 3305 let (func, _) = Parser::new( 3306 "function %foo() system_v { 3307 ss3 = explicit_slot 13 3308 ss1 = explicit_slot 1 3309 }", 3310 ) 3311 .parse_function() 3312 .unwrap(); 3313 assert_eq!(func.name.to_string(), "%foo"); 3314 let mut iter = func.sized_stack_slots.keys(); 3315 let _ss0 = iter.next().unwrap(); 3316 let ss1 = iter.next().unwrap(); 3317 assert_eq!(ss1.to_string(), "ss1"); 3318 assert_eq!( 3319 func.sized_stack_slots[ss1].kind, 3320 StackSlotKind::ExplicitSlot 3321 ); 3322 assert_eq!(func.sized_stack_slots[ss1].size, 1); 3323 let _ss2 = iter.next().unwrap(); 3324 let ss3 = iter.next().unwrap(); 3325 assert_eq!(ss3.to_string(), "ss3"); 3326 assert_eq!( 3327 func.sized_stack_slots[ss3].kind, 3328 StackSlotKind::ExplicitSlot 3329 ); 3330 assert_eq!(func.sized_stack_slots[ss3].size, 13); 3331 assert_eq!(iter.next(), None); 3332 3333 // Catch duplicate definitions. 3334 assert_eq!( 3335 Parser::new( 3336 "function %bar() system_v { 3337 ss1 = explicit_slot 13 3338 ss1 = explicit_slot 1 3339 }", 3340 ) 3341 .parse_function() 3342 .unwrap_err() 3343 .to_string(), 3344 "3: duplicate entity: ss1" 3345 ); 3346 } 3347 3348 #[test] 3349 fn block_header() { 3350 let (func, _) = Parser::new( 3351 "function %blocks() system_v { 3352 block0: 3353 block4(v3: i32): 3354 }", 3355 ) 3356 .parse_function() 3357 .unwrap(); 3358 assert_eq!(func.name.to_string(), "%blocks"); 3359 3360 let mut blocks = func.layout.blocks(); 3361 3362 let block0 = blocks.next().unwrap(); 3363 assert_eq!(func.dfg.block_params(block0), &[]); 3364 3365 let block4 = blocks.next().unwrap(); 3366 let block4_args = func.dfg.block_params(block4); 3367 assert_eq!(block4_args.len(), 1); 3368 assert_eq!(func.dfg.value_type(block4_args[0]), types::I32); 3369 } 3370 3371 #[test] 3372 fn duplicate_block() { 3373 let ParseError { 3374 location, 3375 message, 3376 is_warning, 3377 } = Parser::new( 3378 "function %blocks() system_v { 3379 block0: 3380 block0: 3381 return 2", 3382 ) 3383 .parse_function() 3384 .unwrap_err(); 3385 3386 assert_eq!(location.line_number, 3); 3387 assert_eq!(message, "duplicate entity: block0"); 3388 assert!(!is_warning); 3389 } 3390 3391 #[test] 3392 fn number_of_blocks() { 3393 let ParseError { 3394 location, 3395 message, 3396 is_warning, 3397 } = Parser::new( 3398 "function %a() { 3399 block100000:", 3400 ) 3401 .parse_function() 3402 .unwrap_err(); 3403 3404 assert_eq!(location.line_number, 2); 3405 assert_eq!(message, "too many blocks"); 3406 assert!(!is_warning); 3407 } 3408 3409 #[test] 3410 fn duplicate_ss() { 3411 let ParseError { 3412 location, 3413 message, 3414 is_warning, 3415 } = Parser::new( 3416 "function %blocks() system_v { 3417 ss0 = explicit_slot 8 3418 ss0 = explicit_slot 8", 3419 ) 3420 .parse_function() 3421 .unwrap_err(); 3422 3423 assert_eq!(location.line_number, 3); 3424 assert_eq!(message, "duplicate entity: ss0"); 3425 assert!(!is_warning); 3426 } 3427 3428 #[test] 3429 fn duplicate_gv() { 3430 let ParseError { 3431 location, 3432 message, 3433 is_warning, 3434 } = Parser::new( 3435 "function %blocks() system_v { 3436 gv0 = vmctx 3437 gv0 = vmctx", 3438 ) 3439 .parse_function() 3440 .unwrap_err(); 3441 3442 assert_eq!(location.line_number, 3); 3443 assert_eq!(message, "duplicate entity: gv0"); 3444 assert!(!is_warning); 3445 } 3446 3447 #[test] 3448 fn duplicate_sig() { 3449 let ParseError { 3450 location, 3451 message, 3452 is_warning, 3453 } = Parser::new( 3454 "function %blocks() system_v { 3455 sig0 = () 3456 sig0 = ()", 3457 ) 3458 .parse_function() 3459 .unwrap_err(); 3460 3461 assert_eq!(location.line_number, 3); 3462 assert_eq!(message, "duplicate entity: sig0"); 3463 assert!(!is_warning); 3464 } 3465 3466 #[test] 3467 fn duplicate_fn() { 3468 let ParseError { 3469 location, 3470 message, 3471 is_warning, 3472 } = Parser::new( 3473 "function %blocks() system_v { 3474 sig0 = () 3475 fn0 = %foo sig0 3476 fn0 = %foo sig0", 3477 ) 3478 .parse_function() 3479 .unwrap_err(); 3480 3481 assert_eq!(location.line_number, 4); 3482 assert_eq!(message, "duplicate entity: fn0"); 3483 assert!(!is_warning); 3484 } 3485 3486 #[test] 3487 fn comments() { 3488 let (func, Details { comments, .. }) = Parser::new( 3489 "; before 3490 function %comment() system_v { ; decl 3491 ss10 = explicit_slot 13 ; stackslot. 3492 ; Still stackslot. 3493 block0: ; Basic block 3494 trap user42; Instruction 3495 } ; Trailing. 3496 ; More trailing.", 3497 ) 3498 .parse_function() 3499 .unwrap(); 3500 assert_eq!(func.name.to_string(), "%comment"); 3501 assert_eq!(comments.len(), 7); // no 'before' comment. 3502 assert_eq!( 3503 comments[0], 3504 Comment { 3505 entity: AnyEntity::Function, 3506 text: "; decl", 3507 } 3508 ); 3509 assert_eq!(comments[1].entity.to_string(), "ss10"); 3510 assert_eq!(comments[2].entity.to_string(), "ss10"); 3511 assert_eq!(comments[2].text, "; Still stackslot."); 3512 assert_eq!(comments[3].entity.to_string(), "block0"); 3513 assert_eq!(comments[3].text, "; Basic block"); 3514 3515 assert_eq!(comments[4].entity.to_string(), "inst0"); 3516 assert_eq!(comments[4].text, "; Instruction"); 3517 3518 assert_eq!(comments[5].entity, AnyEntity::Function); 3519 assert_eq!(comments[6].entity, AnyEntity::Function); 3520 } 3521 3522 #[test] 3523 fn test_file() { 3524 let tf = parse_test( 3525 r#"; before 3526 test cfg option=5 3527 test verify 3528 set enable_float=false 3529 feature "foo" 3530 feature !"bar" 3531 ; still preamble 3532 function %comment() system_v {}"#, 3533 ParseOptions::default(), 3534 ) 3535 .unwrap(); 3536 assert_eq!(tf.commands.len(), 2); 3537 assert_eq!(tf.commands[0].command, "cfg"); 3538 assert_eq!(tf.commands[1].command, "verify"); 3539 match tf.isa_spec { 3540 IsaSpec::None(s) => { 3541 assert!(s.enable_verifier()); 3542 assert!(!s.enable_float()); 3543 } 3544 _ => panic!("unexpected ISAs"), 3545 } 3546 assert_eq!(tf.features[0], Feature::With(&"foo")); 3547 assert_eq!(tf.features[1], Feature::Without(&"bar")); 3548 assert_eq!(tf.preamble_comments.len(), 2); 3549 assert_eq!(tf.preamble_comments[0].text, "; before"); 3550 assert_eq!(tf.preamble_comments[1].text, "; still preamble"); 3551 assert_eq!(tf.functions.len(), 1); 3552 assert_eq!(tf.functions[0].0.name.to_string(), "%comment"); 3553 } 3554 3555 #[test] 3556 fn isa_spec() { 3557 assert!(parse_test( 3558 "target 3559 function %foo() system_v {}", 3560 ParseOptions::default() 3561 ) 3562 .is_err()); 3563 3564 assert!(parse_test( 3565 "target x86_64 3566 set enable_float=false 3567 function %foo() system_v {}", 3568 ParseOptions::default() 3569 ) 3570 .is_err()); 3571 3572 match parse_test( 3573 "set enable_float=false 3574 target x86_64 3575 function %foo() system_v {}", 3576 ParseOptions::default(), 3577 ) 3578 .unwrap() 3579 .isa_spec 3580 { 3581 IsaSpec::None(_) => panic!("Expected some ISA"), 3582 IsaSpec::Some(v) => { 3583 assert_eq!(v.len(), 1); 3584 assert!(v[0].name() == "x64" || v[0].name() == "x86"); 3585 } 3586 } 3587 } 3588 3589 #[test] 3590 fn user_function_name() { 3591 // Valid characters in the name: 3592 let func = Parser::new( 3593 "function u1:2() system_v { 3594 block0: 3595 trap int_divz 3596 }", 3597 ) 3598 .parse_function() 3599 .unwrap() 3600 .0; 3601 assert_eq!(func.name.to_string(), "u1:2"); 3602 3603 // Invalid characters in the name: 3604 let mut parser = Parser::new( 3605 "function u123:abc() system_v { 3606 block0: 3607 trap stk_ovf 3608 }", 3609 ); 3610 assert!(parser.parse_function().is_err()); 3611 3612 // Incomplete function names should not be valid: 3613 let mut parser = Parser::new( 3614 "function u() system_v { 3615 block0: 3616 trap int_ovf 3617 }", 3618 ); 3619 assert!(parser.parse_function().is_err()); 3620 3621 let mut parser = Parser::new( 3622 "function u0() system_v { 3623 block0: 3624 trap int_ovf 3625 }", 3626 ); 3627 assert!(parser.parse_function().is_err()); 3628 3629 let mut parser = Parser::new( 3630 "function u0:() system_v { 3631 block0: 3632 trap int_ovf 3633 }", 3634 ); 3635 assert!(parser.parse_function().is_err()); 3636 } 3637 3638 #[test] 3639 fn change_default_calling_convention() { 3640 let code = "function %test() { 3641 block0: 3642 return 3643 }"; 3644 3645 // By default the parser will use the fast calling convention if none is specified. 3646 let mut parser = Parser::new(code); 3647 assert_eq!( 3648 parser.parse_function().unwrap().0.signature.call_conv, 3649 CallConv::Fast 3650 ); 3651 3652 // However, we can specify a different calling convention to be the default. 3653 let mut parser = Parser::new(code).with_default_calling_convention(CallConv::Cold); 3654 assert_eq!( 3655 parser.parse_function().unwrap().0.signature.call_conv, 3656 CallConv::Cold 3657 ); 3658 } 3659 3660 #[test] 3661 fn u8_as_hex() { 3662 fn parse_as_uimm8(text: &str) -> ParseResult<u8> { 3663 Parser::new(text).match_uimm8("unable to parse u8") 3664 } 3665 3666 assert_eq!(parse_as_uimm8("0").unwrap(), 0); 3667 assert_eq!(parse_as_uimm8("0xff").unwrap(), 255); 3668 assert!(parse_as_uimm8("-1").is_err()); 3669 assert!(parse_as_uimm8("0xffa").is_err()); 3670 } 3671 3672 #[test] 3673 fn i16_as_hex() { 3674 fn parse_as_imm16(text: &str) -> ParseResult<i16> { 3675 Parser::new(text).match_imm16("unable to parse i16") 3676 } 3677 3678 assert_eq!(parse_as_imm16("0x8000").unwrap(), -32768); 3679 assert_eq!(parse_as_imm16("0xffff").unwrap(), -1); 3680 assert_eq!(parse_as_imm16("0").unwrap(), 0); 3681 assert_eq!(parse_as_imm16("0x7fff").unwrap(), 32767); 3682 assert_eq!( 3683 parse_as_imm16("-0x0001").unwrap(), 3684 parse_as_imm16("0xffff").unwrap() 3685 ); 3686 assert_eq!( 3687 parse_as_imm16("-0x7fff").unwrap(), 3688 parse_as_imm16("0x8001").unwrap() 3689 ); 3690 assert!(parse_as_imm16("0xffffa").is_err()); 3691 } 3692 3693 #[test] 3694 fn i32_as_hex() { 3695 fn parse_as_imm32(text: &str) -> ParseResult<i32> { 3696 Parser::new(text).match_imm32("unable to parse i32") 3697 } 3698 3699 assert_eq!(parse_as_imm32("0x80000000").unwrap(), -2147483648); 3700 assert_eq!(parse_as_imm32("0xffffffff").unwrap(), -1); 3701 assert_eq!(parse_as_imm32("0").unwrap(), 0); 3702 assert_eq!(parse_as_imm32("0x7fffffff").unwrap(), 2147483647); 3703 assert_eq!( 3704 parse_as_imm32("-0x00000001").unwrap(), 3705 parse_as_imm32("0xffffffff").unwrap() 3706 ); 3707 assert_eq!( 3708 parse_as_imm32("-0x7fffffff").unwrap(), 3709 parse_as_imm32("0x80000001").unwrap() 3710 ); 3711 assert!(parse_as_imm32("0xffffffffa").is_err()); 3712 } 3713 3714 #[test] 3715 fn i64_as_hex() { 3716 fn parse_as_imm64(text: &str) -> ParseResult<Imm64> { 3717 Parser::new(text).match_imm64("unable to parse Imm64") 3718 } 3719 3720 assert_eq!( 3721 parse_as_imm64("0x8000000000000000").unwrap(), 3722 Imm64::new(-9223372036854775808) 3723 ); 3724 assert_eq!( 3725 parse_as_imm64("0xffffffffffffffff").unwrap(), 3726 Imm64::new(-1) 3727 ); 3728 assert_eq!(parse_as_imm64("0").unwrap(), Imm64::new(0)); 3729 assert_eq!( 3730 parse_as_imm64("0x7fffffffffffffff").unwrap(), 3731 Imm64::new(9223372036854775807) 3732 ); 3733 assert_eq!( 3734 parse_as_imm64("-0x0000000000000001").unwrap(), 3735 parse_as_imm64("0xffffffffffffffff").unwrap() 3736 ); 3737 assert_eq!( 3738 parse_as_imm64("-0x7fffffffffffffff").unwrap(), 3739 parse_as_imm64("0x8000000000000001").unwrap() 3740 ); 3741 assert!(parse_as_imm64("0xffffffffffffffffa").is_err()); 3742 } 3743 3744 #[test] 3745 fn uimm128() { 3746 macro_rules! parse_as_constant_data { 3747 ($text:expr, $type:expr) => {{ 3748 Parser::new($text).parse_literals_to_constant_data($type) 3749 }}; 3750 } 3751 macro_rules! can_parse_as_constant_data { 3752 ($text:expr, $type:expr) => {{ 3753 assert!(parse_as_constant_data!($text, $type).is_ok()) 3754 }}; 3755 } 3756 macro_rules! cannot_parse_as_constant_data { 3757 ($text:expr, $type:expr) => {{ 3758 assert!(parse_as_constant_data!($text, $type).is_err()) 3759 }}; 3760 } 3761 3762 can_parse_as_constant_data!("1 2 3 4", I32X4); 3763 can_parse_as_constant_data!("1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16", I8X16); 3764 can_parse_as_constant_data!("0x1.1 0x2.2 0x3.3 0x4.4", F32X4); 3765 can_parse_as_constant_data!("0x0 0x1 0x2 0x3", I32X4); 3766 can_parse_as_constant_data!("-1 0 -1 0 -1 0 -1 0", I16X8); 3767 can_parse_as_constant_data!("0 -1", I64X2); 3768 can_parse_as_constant_data!("-1 0", I64X2); 3769 can_parse_as_constant_data!("-1 -1 -1 -1 -1", I32X4); // note that parse_literals_to_constant_data will leave extra tokens unconsumed 3770 3771 cannot_parse_as_constant_data!("1 2 3", I32X4); 3772 cannot_parse_as_constant_data!(" ", F32X4); 3773 } 3774 3775 #[test] 3776 fn parse_constant_from_booleans() { 3777 let c = Parser::new("-1 0 -1 0") 3778 .parse_literals_to_constant_data(I32X4) 3779 .unwrap(); 3780 assert_eq!( 3781 c.into_vec(), 3782 [0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0] 3783 ) 3784 } 3785 3786 #[test] 3787 fn parse_unbounded_constants() { 3788 // Unlike match_uimm128, match_hexadecimal_constant can parse byte sequences of any size: 3789 assert_eq!( 3790 Parser::new("0x0100") 3791 .match_hexadecimal_constant("err message") 3792 .unwrap(), 3793 vec![0, 1].into() 3794 ); 3795 3796 // Only parse hexadecimal constants: 3797 assert!(Parser::new("228") 3798 .match_hexadecimal_constant("err message") 3799 .is_err()); 3800 } 3801 3802 #[test] 3803 fn parse_run_commands() { 3804 // Helper for creating signatures. 3805 fn sig(ins: &[Type], outs: &[Type]) -> Signature { 3806 let mut sig = Signature::new(CallConv::Fast); 3807 for i in ins { 3808 sig.params.push(AbiParam::new(*i)); 3809 } 3810 for o in outs { 3811 sig.returns.push(AbiParam::new(*o)); 3812 } 3813 sig 3814 } 3815 3816 // Helper for parsing run commands. 3817 fn parse(text: &str, sig: &Signature) -> ParseResult<RunCommand> { 3818 Parser::new(text).parse_run_command(sig) 3819 } 3820 3821 // Check that we can parse and display the same set of run commands. 3822 fn assert_roundtrip(text: &str, sig: &Signature) { 3823 assert_eq!(parse(text, sig).unwrap().to_string(), text); 3824 } 3825 assert_roundtrip("run: %fn0() == 42", &sig(&[], &[I32])); 3826 assert_roundtrip( 3827 "run: %fn0(8, 16, 32, 64) == 1", 3828 &sig(&[I8, I16, I32, I64], &[I8]), 3829 ); 3830 assert_roundtrip( 3831 "run: %my_func(1) == 0x0f0e0d0c0b0a09080706050403020100", 3832 &sig(&[I32], &[I8X16]), 3833 ); 3834 3835 // Verify that default invocations are created when not specified. 3836 assert_eq!( 3837 parse("run", &sig(&[], &[I32])).unwrap().to_string(), 3838 "run: %default() != 0" 3839 ); 3840 assert_eq!( 3841 parse("print", &sig(&[], &[F32X4, I16X8])) 3842 .unwrap() 3843 .to_string(), 3844 "print: %default()" 3845 ); 3846 3847 // Demonstrate some unparsable cases. 3848 assert!(parse("print", &sig(&[I32], &[I32])).is_err()); 3849 assert!(parse("print:", &sig(&[], &[])).is_err()); 3850 assert!(parse("run: ", &sig(&[], &[])).is_err()); 3851 } 3852 3853 #[test] 3854 fn parse_data_values() { 3855 fn parse(text: &str, ty: Type) -> DataValue { 3856 Parser::new(text).parse_data_value(ty).unwrap() 3857 } 3858 3859 assert_eq!(parse("8", I8).to_string(), "8"); 3860 assert_eq!(parse("16", I16).to_string(), "16"); 3861 assert_eq!(parse("32", I32).to_string(), "32"); 3862 assert_eq!(parse("64", I64).to_string(), "64"); 3863 assert_eq!( 3864 parse("0x01234567_01234567_01234567_01234567", I128).to_string(), 3865 "1512366032949150931280199141537564007" 3866 ); 3867 assert_eq!(parse("1234567", I128).to_string(), "1234567"); 3868 assert_eq!(parse("0x32.32", F32).to_string(), "0x1.919000p5"); 3869 assert_eq!(parse("0x64.64", F64).to_string(), "0x1.9190000000000p6"); 3870 assert_eq!( 3871 parse("[0 1 2 3]", I32X4).to_string(), 3872 "0x00000003000000020000000100000000" 3873 ); 3874 } 3875 3876 #[test] 3877 fn parse_cold_blocks() { 3878 let code = "function %test() { 3879 block0 cold: 3880 return 3881 block1(v0: i32) cold: 3882 return 3883 block2(v1: i32): 3884 return 3885 }"; 3886 3887 let mut parser = Parser::new(code); 3888 let func = parser.parse_function().unwrap().0; 3889 assert_eq!(func.layout.blocks().count(), 3); 3890 assert!(func.layout.is_cold(Block::from_u32(0))); 3891 assert!(func.layout.is_cold(Block::from_u32(1))); 3892 assert!(!func.layout.is_cold(Block::from_u32(2))); 3893 } 3894 } 3895