1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
//! A verifier for ensuring that functions are well formed.
//! It verifies:
//!
//! EBB integrity
//!
//! - All instructions reached from the `ebb_insts` iterator must belong to
//!   the EBB as reported by `inst_ebb()`.
//! - Every EBB must end in a terminator instruction, and no other instruction
//!   can be a terminator.
//! - Every value in the `ebb_params` iterator belongs to the EBB as reported by `value_ebb`.
//!
//! Instruction integrity
//!
//! - The instruction format must match the opcode.
//! - All result values must be created for multi-valued instructions.
//! - All referenced entities must exist. (Values, EBBs, stack slots, ...)
//! - Instructions must not reference (eg. branch to) the entry block.
//!
//! SSA form
//!
//! - Values must be defined by an instruction that exists and that is inserted in
//!   an EBB, or be an argument of an existing EBB.
//! - Values used by an instruction must dominate the instruction.
//!
//! Control flow graph and dominator tree integrity:
//!
//! - All predecessors in the CFG must be branches to the EBB.
//! - All branches to an EBB must be present in the CFG.
//! - A recomputed dominator tree is identical to the existing one.
//!
//! Type checking
//!
//! - Compare input and output values against the opcode's type constraints.
//!   For polymorphic opcodes, determine the controlling type variable first.
//! - Branches and jumps must pass arguments to destination EBBs that match the
//!   expected types exactly. The number of arguments must match.
//! - All EBBs in a jump table must take no arguments.
//! - Function calls are type checked against their signature.
//! - The entry block must take arguments that match the signature of the current
//!   function.
//! - All return instructions must have return value operands matching the current
//!   function signature.
//!
//! Global variables
//!
//! - Detect cycles in deref(base) declarations.
//!
//! TODO:
//! Ad hoc checking
//!
//! - Stack slot loads and stores must be in-bounds.
//! - Immediate constraints for certain opcodes, like `udiv_imm v3, 0`.
//! - `Insertlane` and `extractlane` instructions have immediate lane numbers that must be in
//!   range for their polymorphic type.
//! - Swizzle and shuffle instructions take a variable number of lane arguments. The number
//!   of arguments must match the destination type, and the lane indexes must be in range.

use self::flags::verify_flags;
use dbg::DisplayList;
use dominator_tree::DominatorTree;
use entity::SparseSet;
use flowgraph::ControlFlowGraph;
use ir;
use ir::entities::AnyEntity;
use ir::instructions::{BranchInfo, CallInfo, InstructionFormat, ResolvedConstraint};
use ir::{types, ArgumentLoc, Ebb, FuncRef, Function, GlobalVar, Inst, JumpTable, Opcode, SigRef,
         StackSlot, StackSlotKind, Type, Value, ValueDef, ValueList, ValueLoc};
use isa::TargetIsa;
use iterators::IteratorExtras;
use settings::{Flags, FlagsOrIsa};
use std::cmp::Ordering;
use std::collections::BTreeSet;
use std::error as std_error;
use std::fmt::{self, Display, Formatter, Write};
use std::result;
use std::string::String;
use std::vec::Vec;
use timing;

pub use self::cssa::verify_cssa;
pub use self::liveness::verify_liveness;
pub use self::locations::verify_locations;

// Create an `Err` variant of `Result<X>` from a location and `format!` arguments.
macro_rules! err {
    ( $loc:expr, $msg:expr ) => {
        Err(::verifier::Error {
            location: $loc.into(),
            message: String::from($msg),
        })
    };

    ( $loc:expr, $fmt:expr, $( $arg:expr ),+ ) => {
        Err(::verifier::Error {
            location: $loc.into(),
            message: format!( $fmt, $( $arg ),+ ),
        })
    };
}

mod cssa;
mod flags;
mod liveness;
mod locations;

/// A verifier error.
#[derive(Debug, PartialEq, Eq)]
pub struct Error {
    /// The entity causing the verifier error.
    pub location: AnyEntity,
    /// Error message.
    pub message: String,
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "{}: {}", self.location, self.message)
    }
}

impl std_error::Error for Error {
    fn description(&self) -> &str {
        &self.message
    }
}

/// Verifier result.
pub type Result = result::Result<(), Error>;

/// Verify `func`.
pub fn verify_function<'a, FOI: Into<FlagsOrIsa<'a>>>(func: &Function, fisa: FOI) -> Result {
    let _tt = timing::verifier();
    Verifier::new(func, fisa.into()).run()
}

/// Verify `func` after checking the integrity of associated context data structures `cfg` and
/// `domtree`.
pub fn verify_context<'a, FOI: Into<FlagsOrIsa<'a>>>(
    func: &Function,
    cfg: &ControlFlowGraph,
    domtree: &DominatorTree,
    fisa: FOI,
) -> Result {
    let _tt = timing::verifier();
    let verifier = Verifier::new(func, fisa.into());
    if cfg.is_valid() {
        verifier.cfg_integrity(cfg)?;
    }
    if domtree.is_valid() {
        verifier.domtree_integrity(domtree)?;
    }
    verifier.run()
}

struct Verifier<'a> {
    func: &'a Function,
    expected_cfg: ControlFlowGraph,
    expected_domtree: DominatorTree,
    flags: &'a Flags,
    isa: Option<&'a TargetIsa>,
}

impl<'a> Verifier<'a> {
    pub fn new(func: &'a Function, fisa: FlagsOrIsa<'a>) -> Verifier<'a> {
        let expected_cfg = ControlFlowGraph::with_function(func);
        let expected_domtree = DominatorTree::with_function(func, &expected_cfg);
        Verifier {
            func,
            expected_cfg,
            expected_domtree,
            flags: fisa.flags,
            isa: fisa.isa,
        }
    }

    // Check for cycles in the global variable declarations.
    fn verify_global_vars(&self) -> Result {
        let mut seen = SparseSet::new();

        for gv in self.func.global_vars.keys() {
            seen.clear();
            seen.insert(gv);

            let mut cur = gv;
            while let ir::GlobalVarData::Deref { base, .. } = self.func.global_vars[cur] {
                if seen.insert(base).is_some() {
                    return err!(gv, "deref cycle: {}", DisplayList(seen.as_slice()));
                }

                cur = base;
            }
        }

        Ok(())
    }

    fn ebb_integrity(&self, ebb: Ebb, inst: Inst) -> Result {
        let is_terminator = self.func.dfg[inst].opcode().is_terminator();
        let is_last_inst = self.func.layout.last_inst(ebb) == Some(inst);

        if is_terminator && !is_last_inst {
            // Terminating instructions only occur at the end of blocks.
            return err!(
                inst,
                "a terminator instruction was encountered before the end of {}",
                ebb
            );
        }
        if is_last_inst && !is_terminator {
            return err!(ebb, "block does not end in a terminator instruction!");
        }

        // Instructions belong to the correct ebb.
        let inst_ebb = self.func.layout.inst_ebb(inst);
        if inst_ebb != Some(ebb) {
            return err!(inst, "should belong to {} not {:?}", ebb, inst_ebb);
        }

        // Parameters belong to the correct ebb.
        for &arg in self.func.dfg.ebb_params(ebb) {
            match self.func.dfg.value_def(arg) {
                ValueDef::Param(arg_ebb, _) => {
                    if ebb != arg_ebb {
                        return err!(arg, "does not belong to {}", ebb);
                    }
                }
                _ => {
                    return err!(arg, "expected an argument, found a result");
                }
            }
        }

        Ok(())
    }

    fn instruction_integrity(&self, inst: Inst) -> Result {
        let inst_data = &self.func.dfg[inst];
        let dfg = &self.func.dfg;

        // The instruction format matches the opcode
        if inst_data.opcode().format() != InstructionFormat::from(inst_data) {
            return err!(inst, "instruction opcode doesn't match instruction format");
        }

        let fixed_results = inst_data.opcode().constraints().fixed_results();
        // var_results is 0 if we aren't a call instruction
        let var_results = dfg.call_signature(inst).map_or(0, |sig| {
            dfg.signatures[sig].returns.len()
        });
        let total_results = fixed_results + var_results;

        // All result values for multi-valued instructions are created
        let got_results = dfg.inst_results(inst).len();
        if got_results != total_results {
            return err!(
                inst,
                "expected {} result values, found {}",
                total_results,
                got_results
            );
        }

        self.verify_entity_references(inst)
    }

    fn verify_entity_references(&self, inst: Inst) -> Result {
        use ir::instructions::InstructionData::*;

        for &arg in self.func.dfg.inst_args(inst) {
            self.verify_inst_arg(inst, arg)?;

            // All used values must be attached to something.
            let original = self.func.dfg.resolve_aliases(arg);
            if !self.func.dfg.value_is_attached(original) {
                return err!(inst, "argument {} -> {} is not attached", arg, original);
            }
        }

        for &res in self.func.dfg.inst_results(inst) {
            self.verify_inst_result(inst, res)?;
        }

        match self.func.dfg[inst] {
            MultiAry { ref args, .. } => {
                self.verify_value_list(inst, args)?;
            }
            Jump {
                destination,
                ref args,
                ..
            } |
            Branch {
                destination,
                ref args,
                ..
            } |
            BranchInt {
                destination,
                ref args,
                ..
            } |
            BranchFloat {
                destination,
                ref args,
                ..
            } |
            BranchIcmp {
                destination,
                ref args,
                ..
            } => {
                self.verify_ebb(inst, destination)?;
                self.verify_value_list(inst, args)?;
            }
            BranchTable { table, .. } => {
                self.verify_jump_table(inst, table)?;
            }
            Call { func_ref, ref args, .. } => {
                self.verify_func_ref(inst, func_ref)?;
                self.verify_value_list(inst, args)?;
            }
            CallIndirect { sig_ref, ref args, .. } => {
                self.verify_sig_ref(inst, sig_ref)?;
                self.verify_value_list(inst, args)?;
            }
            FuncAddr { func_ref, .. } => {
                self.verify_func_ref(inst, func_ref)?;
            }
            StackLoad { stack_slot, .. } |
            StackStore { stack_slot, .. } => {
                self.verify_stack_slot(inst, stack_slot)?;
            }
            UnaryGlobalVar { global_var, .. } => {
                self.verify_global_var(inst, global_var)?;
            }
            HeapAddr { heap, .. } => {
                self.verify_heap(inst, heap)?;
            }
            RegSpill { dst, .. } => {
                self.verify_stack_slot(inst, dst)?;
            }
            RegFill { src, .. } => {
                self.verify_stack_slot(inst, src)?;
            }

            // Exhaustive list so we can't forget to add new formats
            Unary { .. } |
            UnaryImm { .. } |
            UnaryIeee32 { .. } |
            UnaryIeee64 { .. } |
            UnaryBool { .. } |
            Binary { .. } |
            BinaryImm { .. } |
            Ternary { .. } |
            InsertLane { .. } |
            ExtractLane { .. } |
            IntCompare { .. } |
            IntCompareImm { .. } |
            IntCond { .. } |
            FloatCompare { .. } |
            FloatCond { .. } |
            IntSelect { .. } |
            Load { .. } |
            Store { .. } |
            RegMove { .. } |
            CopySpecial { .. } |
            Trap { .. } |
            CondTrap { .. } |
            IntCondTrap { .. } |
            FloatCondTrap { .. } |
            NullAry { .. } => {}
        }

        Ok(())
    }

    fn verify_ebb(&self, inst: Inst, e: Ebb) -> Result {
        if !self.func.dfg.ebb_is_valid(e) || !self.func.layout.is_ebb_inserted(e) {
            return err!(inst, "invalid ebb reference {}", e);
        }
        if let Some(entry_block) = self.func.layout.entry_block() {
            if e == entry_block {
                return err!(inst, "invalid reference to entry ebb {}", e);
            }
        }
        Ok(())
    }

    fn verify_sig_ref(&self, inst: Inst, s: SigRef) -> Result {
        if !self.func.dfg.signatures.is_valid(s) {
            err!(inst, "invalid signature reference {}", s)
        } else {
            Ok(())
        }
    }

    fn verify_func_ref(&self, inst: Inst, f: FuncRef) -> Result {
        if !self.func.dfg.ext_funcs.is_valid(f) {
            err!(inst, "invalid function reference {}", f)
        } else {
            Ok(())
        }
    }

    fn verify_stack_slot(&self, inst: Inst, ss: StackSlot) -> Result {
        if !self.func.stack_slots.is_valid(ss) {
            err!(inst, "invalid stack slot {}", ss)
        } else {
            Ok(())
        }
    }

    fn verify_global_var(&self, inst: Inst, gv: GlobalVar) -> Result {
        if !self.func.global_vars.is_valid(gv) {
            err!(inst, "invalid global variable {}", gv)
        } else {
            Ok(())
        }
    }

    fn verify_heap(&self, inst: Inst, heap: ir::Heap) -> Result {
        if !self.func.heaps.is_valid(heap) {
            err!(inst, "invalid heap {}", heap)
        } else {
            Ok(())
        }
    }

    fn verify_value_list(&self, inst: Inst, l: &ValueList) -> Result {
        if !l.is_valid(&self.func.dfg.value_lists) {
            err!(inst, "invalid value list reference {:?}", l)
        } else {
            Ok(())
        }
    }

    fn verify_jump_table(&self, inst: Inst, j: JumpTable) -> Result {
        if !self.func.jump_tables.is_valid(j) {
            err!(inst, "invalid jump table reference {}", j)
        } else {
            Ok(())
        }
    }

    fn verify_value(&self, loc_inst: Inst, v: Value) -> Result {
        let dfg = &self.func.dfg;
        if !dfg.value_is_valid(v) {
            err!(loc_inst, "invalid value reference {}", v)
        } else {
            Ok(())
        }
    }

    fn verify_inst_arg(&self, loc_inst: Inst, v: Value) -> Result {
        self.verify_value(loc_inst, v)?;

        let dfg = &self.func.dfg;
        let loc_ebb = self.func.layout.pp_ebb(loc_inst);
        let is_reachable = self.expected_domtree.is_reachable(loc_ebb);

        // SSA form
        match dfg.value_def(v) {
            ValueDef::Result(def_inst, _) => {
                // Value is defined by an instruction that exists.
                if !dfg.inst_is_valid(def_inst) {
                    return err!(
                        loc_inst,
                        "{} is defined by invalid instruction {}",
                        v,
                        def_inst
                    );
                }
                // Defining instruction is inserted in an EBB.
                if self.func.layout.inst_ebb(def_inst) == None {
                    return err!(
                        loc_inst,
                        "{} is defined by {} which has no EBB",
                        v,
                        def_inst
                    );
                }
                // Defining instruction dominates the instruction that uses the value.
                if is_reachable {
                    if !self.expected_domtree.dominates(
                        def_inst,
                        loc_inst,
                        &self.func.layout,
                    )
                    {
                        return err!(loc_inst, "uses value from non-dominating {}", def_inst);
                    }
                    if def_inst == loc_inst {
                        return err!(
                            loc_inst,
                            "uses value from itself {},  {}",
                            def_inst,
                            loc_inst
                        );
                    }
                }
            }
            ValueDef::Param(ebb, _) => {
                // Value is defined by an existing EBB.
                if !dfg.ebb_is_valid(ebb) {
                    return err!(loc_inst, "{} is defined by invalid EBB {}", v, ebb);
                }
                // Defining EBB is inserted in the layout
                if !self.func.layout.is_ebb_inserted(ebb) {
                    return err!(
                        loc_inst,
                        "{} is defined by {} which is not in the layout",
                        v,
                        ebb
                    );
                }
                // The defining EBB dominates the instruction using this value.
                if is_reachable &&
                    !self.expected_domtree.dominates(
                        ebb,
                        loc_inst,
                        &self.func.layout,
                    )
                {
                    return err!(loc_inst, "uses value arg from non-dominating {}", ebb);
                }
            }
        }
        Ok(())
    }

    fn verify_inst_result(&self, loc_inst: Inst, v: Value) -> Result {
        self.verify_value(loc_inst, v)?;

        match self.func.dfg.value_def(v) {
            ValueDef::Result(def_inst, _) => {
                if def_inst != loc_inst {
                    err!(
                        loc_inst,
                        "instruction result {} is not defined by the instruction",
                        v
                    )
                } else {
                    Ok(())
                }
            }
            ValueDef::Param(_, _) => {
                err!(
                    loc_inst,
                    "instruction result {} is not defined by the instruction",
                    v
                )
            }
        }
    }

    fn domtree_integrity(&self, domtree: &DominatorTree) -> Result {
        // We consider two `DominatorTree`s to be equal if they return the same immediate
        // dominator for each EBB. Therefore the current domtree is valid if it matches the freshly
        // computed one.
        for ebb in self.func.layout.ebbs() {
            let expected = self.expected_domtree.idom(ebb);
            let got = domtree.idom(ebb);
            if got != expected {
                return err!(
                    ebb,
                    "invalid domtree, expected idom({}) = {:?}, got {:?}",
                    ebb,
                    expected,
                    got
                );
            }
        }
        // We also verify if the postorder defined by `DominatorTree` is sane
        if domtree.cfg_postorder().len() != self.expected_domtree.cfg_postorder().len() {
            return err!(
                AnyEntity::Function,
                "incorrect number of Ebbs in postorder traversal"
            );
        }
        for (index, (&test_ebb, &true_ebb)) in
            domtree
                .cfg_postorder()
                .iter()
                .zip(self.expected_domtree.cfg_postorder().iter())
                .enumerate()
        {
            if test_ebb != true_ebb {
                return err!(
                    test_ebb,
                    "invalid domtree, postorder ebb number {} should be {}, got {}",
                    index,
                    true_ebb,
                    test_ebb
                );
            }
        }
        // We verify rpo_cmp on pairs of adjacent ebbs in the postorder
        for (&prev_ebb, &next_ebb) in domtree.cfg_postorder().iter().adjacent_pairs() {
            if self.expected_domtree.rpo_cmp(
                prev_ebb,
                next_ebb,
                &self.func.layout,
            ) != Ordering::Greater
            {
                return err!(
                    next_ebb,
                    "invalid domtree, rpo_cmp does not says {} is greater than {}",
                    prev_ebb,
                    next_ebb
                );
            }
        }
        Ok(())
    }

    fn typecheck_entry_block_params(&self) -> Result {
        if let Some(ebb) = self.func.layout.entry_block() {
            let expected_types = &self.func.signature.params;
            let ebb_param_count = self.func.dfg.num_ebb_params(ebb);

            if ebb_param_count != expected_types.len() {
                return err!(
                    ebb,
                    "entry block parameters ({}) must match function signature ({})",
                    ebb_param_count,
                    expected_types.len()
                );
            }

            for (i, &arg) in self.func.dfg.ebb_params(ebb).iter().enumerate() {
                let arg_type = self.func.dfg.value_type(arg);
                if arg_type != expected_types[i].value_type {
                    return err!(
                        ebb,
                        "entry block parameter {} expected to have type {}, got {}",
                        i,
                        expected_types[i],
                        arg_type
                    );
                }
            }
        }
        Ok(())
    }

    fn typecheck(&self, inst: Inst) -> Result {
        let inst_data = &self.func.dfg[inst];
        let constraints = inst_data.opcode().constraints();

        let ctrl_type = if let Some(value_typeset) = constraints.ctrl_typeset() {
            // For polymorphic opcodes, determine the controlling type variable first.
            let ctrl_type = self.func.dfg.ctrl_typevar(inst);

            if !value_typeset.contains(ctrl_type) {
                return err!(inst, "has an invalid controlling type {}", ctrl_type);
            }

            ctrl_type
        } else {
            // Non-polymorphic instructions don't check the controlling type variable, so `Option`
            // is unnecessary and we can just make it `VOID`.
            types::VOID
        };

        self.typecheck_results(inst, ctrl_type)?;
        self.typecheck_fixed_args(inst, ctrl_type)?;
        self.typecheck_variable_args(inst)?;
        self.typecheck_return(inst)?;
        self.typecheck_special(inst, ctrl_type)?;

        Ok(())
    }

    fn typecheck_results(&self, inst: Inst, ctrl_type: Type) -> Result {
        let mut i = 0;
        for &result in self.func.dfg.inst_results(inst) {
            let result_type = self.func.dfg.value_type(result);
            let expected_type = self.func.dfg.compute_result_type(inst, i, ctrl_type);
            if let Some(expected_type) = expected_type {
                if result_type != expected_type {
                    return err!(
                        inst,
                        "expected result {} ({}) to have type {}, found {}",
                        i,
                        result,
                        expected_type,
                        result_type
                    );
                }
            } else {
                return err!(inst, "has more result values than expected");
            }
            i += 1;
        }

        // There aren't any more result types left.
        if self.func.dfg.compute_result_type(inst, i, ctrl_type) != None {
            return err!(inst, "has fewer result values than expected");
        }
        Ok(())
    }

    fn typecheck_fixed_args(&self, inst: Inst, ctrl_type: Type) -> Result {
        let constraints = self.func.dfg[inst].opcode().constraints();

        for (i, &arg) in self.func.dfg.inst_fixed_args(inst).iter().enumerate() {
            let arg_type = self.func.dfg.value_type(arg);
            match constraints.value_argument_constraint(i, ctrl_type) {
                ResolvedConstraint::Bound(expected_type) => {
                    if arg_type != expected_type {
                        return err!(
                            inst,
                            "arg {} ({}) has type {}, expected {}",
                            i,
                            arg,
                            arg_type,
                            expected_type
                        );
                    }
                }
                ResolvedConstraint::Free(type_set) => {
                    if !type_set.contains(arg_type) {
                        return err!(
                            inst,
                            "arg {} ({}) with type {} failed to satisfy type set {:?}",
                            i,
                            arg,
                            arg_type,
                            type_set
                        );
                    }
                }
            }
        }
        Ok(())
    }

    fn typecheck_variable_args(&self, inst: Inst) -> Result {
        match self.func.dfg.analyze_branch(inst) {
            BranchInfo::SingleDest(ebb, _) => {
                let iter = self.func.dfg.ebb_params(ebb).iter().map(|&v| {
                    self.func.dfg.value_type(v)
                });
                self.typecheck_variable_args_iterator(inst, iter)?;
            }
            BranchInfo::Table(table) => {
                for (_, ebb) in self.func.jump_tables[table].entries() {
                    let arg_count = self.func.dfg.num_ebb_params(ebb);
                    if arg_count != 0 {
                        return err!(
                            inst,
                            "takes no arguments, but had target {} with {} arguments",
                            ebb,
                            arg_count
                        );
                    }
                }
            }
            BranchInfo::NotABranch => {}
        }

        match self.func.dfg[inst].analyze_call(&self.func.dfg.value_lists) {
            CallInfo::Direct(func_ref, _) => {
                let sig_ref = self.func.dfg.ext_funcs[func_ref].signature;
                let arg_types = self.func.dfg.signatures[sig_ref].params.iter().map(|a| {
                    a.value_type
                });
                self.typecheck_variable_args_iterator(inst, arg_types)?;
                self.check_outgoing_args(inst, sig_ref)?;
            }
            CallInfo::Indirect(sig_ref, _) => {
                let arg_types = self.func.dfg.signatures[sig_ref].params.iter().map(|a| {
                    a.value_type
                });
                self.typecheck_variable_args_iterator(inst, arg_types)?;
                self.check_outgoing_args(inst, sig_ref)?;
            }
            CallInfo::NotACall => {}
        }
        Ok(())
    }

    fn typecheck_variable_args_iterator<I: Iterator<Item = Type>>(
        &self,
        inst: Inst,
        iter: I,
    ) -> Result {
        let variable_args = self.func.dfg.inst_variable_args(inst);
        let mut i = 0;

        for expected_type in iter {
            if i >= variable_args.len() {
                // Result count mismatch handled below, we want the full argument count first though
                i += 1;
                continue;
            }
            let arg = variable_args[i];
            let arg_type = self.func.dfg.value_type(arg);
            if expected_type != arg_type {
                return err!(
                    inst,
                    "arg {} ({}) has type {}, expected {}",
                    i,
                    variable_args[i],
                    arg_type,
                    expected_type
                );
            }
            i += 1;
        }
        if i != variable_args.len() {
            return err!(
                inst,
                "mismatched argument count, got {}, expected {}",
                variable_args.len(),
                i
            );
        }
        Ok(())
    }

    /// Check the locations assigned to outgoing call arguments.
    ///
    /// When a signature has been legalized, all values passed as outgoing arguments on the stack
    /// must be assigned to a matching `OutgoingArg` stack slot.
    fn check_outgoing_args(&self, inst: Inst, sig_ref: SigRef) -> Result {
        let sig = &self.func.dfg.signatures[sig_ref];

        // Before legalization, there's nothing to check.
        if sig.argument_bytes.is_none() {
            return Ok(());
        }

        let args = self.func.dfg.inst_variable_args(inst);
        let expected_args = &sig.params[..];

        for (&arg, &abi) in args.iter().zip(expected_args) {
            // Value types have already been checked by `typecheck_variable_args_iterator()`.
            if let ArgumentLoc::Stack(offset) = abi.location {
                let arg_loc = self.func.locations[arg];
                if let ValueLoc::Stack(ss) = arg_loc {
                    // Argument value is assigned to a stack slot as expected.
                    self.verify_stack_slot(inst, ss)?;
                    let slot = &self.func.stack_slots[ss];
                    if slot.kind != StackSlotKind::OutgoingArg {
                        return err!(
                            inst,
                            "Outgoing stack argument {} in wrong stack slot: {} = {}",
                            arg,
                            ss,
                            slot
                        );
                    }
                    if slot.offset != Some(offset) {
                        return err!(
                            inst,
                            "Outgoing stack argument {} should have offset {}: {} = {}",
                            arg,
                            offset,
                            ss,
                            slot
                        );
                    }
                    if slot.size != abi.value_type.bytes() {
                        return err!(
                            inst,
                            "Outgoing stack argument {} wrong size for {}: {} = {}",
                            arg,
                            abi.value_type,
                            ss,
                            slot
                        );
                    }
                } else {
                    let reginfo = self.isa.map(|i| i.register_info());
                    return err!(
                        inst,
                        "Outgoing stack argument {} in wrong location: {}",
                        arg,
                        arg_loc.display(reginfo.as_ref())
                    );
                }
            }
        }
        Ok(())
    }

    fn typecheck_return(&self, inst: Inst) -> Result {
        if self.func.dfg[inst].opcode().is_return() {
            let args = self.func.dfg.inst_variable_args(inst);
            let expected_types = &self.func.signature.returns;
            if args.len() != expected_types.len() {
                return err!(inst, "arguments of return must match function signature");
            }
            for (i, (&arg, &expected_type)) in args.iter().zip(expected_types).enumerate() {
                let arg_type = self.func.dfg.value_type(arg);
                if arg_type != expected_type.value_type {
                    return err!(
                        inst,
                        "arg {} ({}) has type {}, must match function signature of {}",
                        i,
                        arg,
                        arg_type,
                        expected_type
                    );
                }
            }
        }
        Ok(())
    }

    // Check special-purpose type constraints that can't be expressed in the normal opcode
    // constraints.
    fn typecheck_special(&self, inst: Inst, ctrl_type: Type) -> Result {
        if let ir::InstructionData::Unary { opcode, arg } = self.func.dfg[inst] {
            let arg_type = self.func.dfg.value_type(arg);
            match opcode {
                Opcode::Bextend | Opcode::Uextend | Opcode::Sextend | Opcode::Fpromote => {
                    if arg_type.lane_count() != ctrl_type.lane_count() {
                        return err!(
                            inst,
                            "input {} and output {} must have same number of lanes",
                            arg_type,
                            ctrl_type
                        );
                    }
                    if arg_type.lane_bits() >= ctrl_type.lane_bits() {
                        return err!(
                            inst,
                            "input {} must be smaller than output {}",
                            arg_type,
                            ctrl_type
                        );
                    }
                }
                Opcode::Breduce | Opcode::Ireduce | Opcode::Fdemote => {
                    if arg_type.lane_count() != ctrl_type.lane_count() {
                        return err!(
                            inst,
                            "input {} and output {} must have same number of lanes",
                            arg_type,
                            ctrl_type
                        );
                    }
                    if arg_type.lane_bits() <= ctrl_type.lane_bits() {
                        return err!(
                            inst,
                            "input {} must be larger than output {}",
                            arg_type,
                            ctrl_type
                        );
                    }
                }
                _ => {}
            }
        }
        Ok(())
    }

    fn cfg_integrity(&self, cfg: &ControlFlowGraph) -> Result {
        let mut expected_succs = BTreeSet::<Ebb>::new();
        let mut got_succs = BTreeSet::<Ebb>::new();
        let mut expected_preds = BTreeSet::<Inst>::new();
        let mut got_preds = BTreeSet::<Inst>::new();

        for ebb in self.func.layout.ebbs() {
            expected_succs.extend(self.expected_cfg.succ_iter(ebb));
            got_succs.extend(cfg.succ_iter(ebb));

            let missing_succs: Vec<Ebb> = expected_succs.difference(&got_succs).cloned().collect();
            if !missing_succs.is_empty() {
                return err!(
                    ebb,
                    "cfg lacked the following successor(s) {:?}",
                    missing_succs
                );
            }

            let excess_succs: Vec<Ebb> = got_succs.difference(&expected_succs).cloned().collect();
            if !excess_succs.is_empty() {
                return err!(ebb, "cfg had unexpected successor(s) {:?}", excess_succs);
            }

            expected_preds.extend(self.expected_cfg.pred_iter(ebb).map(|(_, inst)| inst));
            got_preds.extend(cfg.pred_iter(ebb).map(|(_, inst)| inst));

            let missing_preds: Vec<Inst> = expected_preds.difference(&got_preds).cloned().collect();
            if !missing_preds.is_empty() {
                return err!(
                    ebb,
                    "cfg lacked the following predecessor(s) {:?}",
                    missing_preds
                );
            }

            let excess_preds: Vec<Inst> = got_preds.difference(&expected_preds).cloned().collect();
            if !excess_preds.is_empty() {
                return err!(ebb, "cfg had unexpected predecessor(s) {:?}", excess_preds);
            }

            expected_succs.clear();
            got_succs.clear();
            expected_preds.clear();
            got_preds.clear();
        }
        Ok(())
    }

    /// If the verifier has been set up with an ISA, make sure that the recorded encoding for the
    /// instruction (if any) matches how the ISA would encode it.
    fn verify_encoding(&self, inst: Inst) -> Result {
        // When the encodings table is empty, we don't require any instructions to be encoded.
        //
        // Once some instructions are encoded, we require all side-effecting instructions to have a
        // legal encoding.
        if self.func.encodings.is_empty() {
            return Ok(());
        }

        let isa = match self.isa {
            Some(isa) => isa,
            None => return Ok(()),
        };

        let encoding = self.func.encodings[inst];
        if encoding.is_legal() {
            let mut encodings = isa.legal_encodings(
                &self.func,
                &self.func.dfg[inst],
                self.func.dfg.ctrl_typevar(inst),
            ).peekable();

            if encodings.peek().is_none() {
                return err!(
                    inst,
                    "Instruction failed to re-encode {}",
                    isa.encoding_info().display(encoding)
                );
            }

            let has_valid_encoding = encodings.any(|possible_enc| encoding == possible_enc);

            if !has_valid_encoding {
                let mut possible_encodings = String::new();
                let mut multiple_encodings = false;

                for enc in isa.legal_encodings(
                    &self.func,
                    &self.func.dfg[inst],
                    self.func.dfg.ctrl_typevar(inst),
                )
                {
                    if !possible_encodings.is_empty() {
                        possible_encodings.push_str(", ");
                        multiple_encodings = true;
                    }
                    possible_encodings
                        .write_fmt(format_args!("{}", isa.encoding_info().display(enc)))
                        .unwrap();
                }

                return err!(
                    inst,
                    "encoding {} should be {}{}",
                    isa.encoding_info().display(encoding),
                    if multiple_encodings { "one of: " } else { "" },
                    possible_encodings
                );
            }
            return Ok(());
        }

        // Instruction is not encoded, so it is a ghost instruction.
        // Instructions with side effects are not allowed to be ghost instructions.
        let opcode = self.func.dfg[inst].opcode();

        // The `fallthrough` instruction is marked as a terminator and a branch, but it is not
        // required to have an encoding.
        if opcode == Opcode::Fallthrough {
            return Ok(());
        }

        // Check if this opcode must be encoded.
        let mut needs_enc = None;
        if opcode.is_branch() {
            needs_enc = Some("Branch");
        } else if opcode.is_call() {
            needs_enc = Some("Call");
        } else if opcode.is_return() {
            needs_enc = Some("Return");
        } else if opcode.can_store() {
            needs_enc = Some("Store");
        } else if opcode.can_trap() {
            needs_enc = Some("Trapping instruction");
        } else if opcode.other_side_effects() {
            needs_enc = Some("Instruction with side effects");
        }

        if let Some(text) = needs_enc {
            // This instruction needs an encoding, so generate an error.
            // Provide the ISA default encoding as a hint.
            match self.func.encode(inst, isa) {
                Ok(enc) => {
                    return err!(
                        inst,
                        "{} must have an encoding (e.g., {})",
                        text,
                        isa.encoding_info().display(enc)
                    )
                }
                Err(_) => return err!(inst, "{} must have an encoding", text),
            }
        }

        Ok(())
    }

    /// Verify the `return_at_end` property which requires that there are no internal return
    /// instructions.
    fn verify_return_at_end(&self) -> Result {
        for ebb in self.func.layout.ebbs() {
            let inst = self.func.layout.last_inst(ebb).unwrap();
            if self.func.dfg[inst].opcode().is_return() &&
                Some(ebb) != self.func.layout.last_ebb()
            {
                return err!(inst, "Internal return not allowed with return_at_end=1");
            }
        }

        Ok(())
    }

    pub fn run(&self) -> Result {
        self.verify_global_vars()?;
        self.typecheck_entry_block_params()?;
        for ebb in self.func.layout.ebbs() {
            for inst in self.func.layout.ebb_insts(ebb) {
                self.ebb_integrity(ebb, inst)?;
                self.instruction_integrity(inst)?;
                self.typecheck(inst)?;
                self.verify_encoding(inst)?;
            }
        }

        if self.flags.return_at_end() {
            self.verify_return_at_end()?;
        }

        verify_flags(self.func, &self.expected_cfg, self.isa)?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::{Error, Verifier};
    use entity::EntityList;
    use ir::Function;
    use ir::instructions::{InstructionData, Opcode};
    use settings;

    macro_rules! assert_err_with_msg {
        ($e:expr, $msg:expr) => {
            match $e {
                Ok(_) => panic!("Expected an error!"),
                Err(Error { message, .. }) => {
                    if !message.contains($msg) {
                        panic!(format!(
                            "'{}' did not contain the substring '{}'",
                            message, $msg
                        ));
                    }
                }
            }
        };
    }

    #[test]
    fn empty() {
        let func = Function::new();
        let flags = &settings::Flags::new(&settings::builder());
        let verifier = Verifier::new(&func, flags.into());
        assert_eq!(verifier.run(), Ok(()));
    }

    #[test]
    fn bad_instruction_format() {
        let mut func = Function::new();
        let ebb0 = func.dfg.make_ebb();
        func.layout.append_ebb(ebb0);
        let nullary_with_bad_opcode = func.dfg.make_inst(InstructionData::UnaryImm {
            opcode: Opcode::F32const,
            imm: 0.into(),
        });
        func.layout.append_inst(nullary_with_bad_opcode, ebb0);
        func.layout.append_inst(
            func.dfg.make_inst(InstructionData::Jump {
                opcode: Opcode::Jump,
                destination: ebb0,
                args: EntityList::default(),
            }),
            ebb0,
        );
        let flags = &settings::Flags::new(&settings::builder());
        let verifier = Verifier::new(&func, flags.into());
        assert_err_with_msg!(verifier.run(), "instruction format");
    }
}