<commit_before>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use llvm::{self, BasicBlock};
use rustc::middle::lang_items;
use rustc::ty::{self, Ty, TypeFoldable};
use rustc::ty::layout::{self, LayoutOf};
use rustc::mir;
use rustc::mir::interpret::EvalErrorKind;
use abi::{Abi, ArgType, ArgTypeExt, FnType, FnTypeExt, LlvmType, PassMode};
use base;
use callee;
use builder::{Builder, MemFlags};
use common::{self, C_bool, C_str_slice, C_struct, C_u32, C_uint_big, C_undef};
use consts;
use meth;
use monomorphize;
use type_of::LayoutLlvmExt;
use type_::Type;
use value::Value;

use syntax::symbol::Symbol;
use syntax_pos::Pos;

use super::{FunctionCx, LocalRef};
use super::place::PlaceRef;
use super::operand::OperandRef;
use super::operand::OperandValue::{Pair, Ref, Immediate};

impl FunctionCx<'a, 'll, 'tcx> {
    pub fn codegen_block(&mut self, bb: mir::BasicBlock) {
        let mut bx = self.build_block(bb);
        let data = &self.mir[bb];

        debug!("codegen_block({:?}={:?})", bb, data);

        for statement in &data.statements {
            bx = self.codegen_statement(bx, statement);
        }

        self.codegen_terminator(bx, bb, data.terminator());
    }

    fn codegen_terminator(&mut self,
                        mut bx: Builder<'a, 'll, 'tcx>,
                        bb: mir::BasicBlock,
                        terminator: &mir::Terminator<'tcx>)
    {
        debug!("codegen_terminator: {:?}", terminator);

        // Create the cleanup bundle, if needed.
        let tcx = bx.tcx();
        let span = terminator.source_info.span;
        let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
        let funclet = funclet_bb.and_then(|funclet_bb| self.funclets[funclet_bb].as_ref());

        let cleanup_pad = funclet.map(|lp| lp.cleanuppad());
        let cleanup_bundle = funclet.map(|l| l.bundle());

        let lltarget = |this: &mut Self, target: mir::BasicBlock| {
            let lltarget = this.blocks[target];
            let target_funclet = this.cleanup_kinds[target].funclet_bb(target);
            match (funclet_bb, target_funclet) {
                (None, None) => (lltarget, false),
                (Some(f), Some(t_f))
                    if f == t_f || !base::wants_msvc_seh(tcx.sess)
                    => (lltarget, false),
                (None, Some(_)) => {
                    // jump *into* cleanup - need a landing pad if GNU
                    (this.landing_pad_to(target), false)
                }
                (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", terminator),
                (Some(_), Some(_)) => {
                    (this.landing_pad_to(target), true)
                }
            }
        };

        let llblock = |this: &mut Self, target: mir::BasicBlock| {
            let (lltarget, is_cleanupret) = lltarget(this, target);
            if is_cleanupret {
                // MSVC cross-funclet jump - need a trampoline

                debug!("llblock: creating cleanup trampoline for {:?}", target);
                let name = &format!("{:?}_cleanup_trampoline_{:?}", bb, target);
                let trampoline = this.new_block(name);
                trampoline.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
                trampoline.llbb()
            } else {
                lltarget
            }
        };

        let funclet_br = |this: &mut Self, bx: Builder<'_, 'll, '_>, target: mir::BasicBlock| {
            let (lltarget, is_cleanupret) = lltarget(this, target);
            if is_cleanupret {
                // micro-optimization: generate a `ret` rather than a jump
                // to a trampoline.
                bx.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
            } else {
                bx.br(lltarget);
            }
        };

        let do_call = |
            this: &mut Self,
            bx: Builder<'a, 'll, 'tcx>,
            fn_ty: FnType<'tcx, Ty<'tcx>>,
            fn_ptr: &'ll Value,
            llargs: &[&'ll Value],
            destination: Option<(ReturnDest<'ll, 'tcx>, mir::BasicBlock)>,
            cleanup: Option<mir::BasicBlock>
        | {
            if let Some(cleanup) = cleanup {
                let ret_bx = if let Some((_, target)) = destination {
                    this.blocks[target]
                } else {
                    this.unreachable_block()
                };
                let invokeret = bx.invoke(fn_ptr,
                                           &llargs,
                                           ret_bx,
                                           llblock(this, cleanup),
                                           cleanup_bundle);
                fn_ty.apply_attrs_callsite(&bx, invokeret);

                if let Some((ret_dest, target)) = destination {
                    let ret_bx = this.build_block(target);
                    this.set_debug_loc(&ret_bx, terminator.source_info);
                    this.store_return(&ret_bx, ret_dest, &fn_ty.ret, invokeret);
                }
            } else {
                let llret = bx.call(fn_ptr, &llargs, cleanup_bundle);
                fn_ty.apply_attrs_callsite(&bx, llret);
                if this.mir[bb].is_cleanup {
                    // Cleanup is always the cold path. Don't inline
                    // drop glue. Also, when there is a deeply-nested
                    // struct, there are "symmetry" issues that cause
                    // exponential inlining - see issue #41696.
                    llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret);
                }

                if let Some((ret_dest, target)) = destination {
                    this.store_return(&bx, ret_dest, &fn_ty.ret, llret);
                    funclet_br(this, bx, target);
                } else {
                    bx.unreachable();
                }
            }
        };

        self.set_debug_loc(&bx, terminator.source_info);
        match terminator.kind {
            mir::TerminatorKind::Resume => {
                if let Some(cleanup_pad) = cleanup_pad {
                    bx.cleanup_ret(cleanup_pad, None);
                } else {
                    let slot = self.get_personality_slot(&bx);
                    let lp0 = slot.project_field(&bx, 0).load(&bx).immediate();
                    let lp1 = slot.project_field(&bx, 1).load(&bx).immediate();
                    slot.storage_dead(&bx);

                    if !bx.sess().target.target.options.custom_unwind_resume {
                        let mut lp = C_undef(self.landing_pad_type());
                        lp = bx.insert_value(lp, lp0, 0);
                        lp = bx.insert_value(lp, lp1, 1);
                        bx.resume(lp);
                    } else {
                        bx.call(bx.cx.eh_unwind_resume(), &[lp0], cleanup_bundle);
                        bx.unreachable();
                    }
                }
            }

            mir::TerminatorKind::Abort => {
                // Call core::intrinsics::abort()
                let fnname = bx.cx.get_intrinsic(&("llvm.trap"));
                bx.call(fnname, &[], None);
                bx.unreachable();
            }

            mir::TerminatorKind::Goto { target } => {
                funclet_br(self, bx, target);
            }

            mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
                let discr = self.codegen_operand(&bx, discr);
                if targets.len() == 2 {
                    // If there are two targets, emit br instead of switch
                    let lltrue = llblock(self, targets[0]);
                    let llfalse = llblock(self, targets[1]);
                    if switch_ty == bx.tcx().types.bool {
                        // Don't generate trivial icmps when switching on bool
                        if let [0] = values[..] {
                            bx.cond_br(discr.immediate(), llfalse, lltrue);
                        } else {
                            assert_eq!(&values[..], &[1]);
                            bx.cond_br(discr.immediate(), lltrue, llfalse);
                        }
                    } else {
                        let switch_llty = bx.cx.layout_of(switch_ty).immediate_llvm_type(bx.cx);
                        let llval = C_uint_big(switch_llty, values[0]);
                        let cmp = bx.icmp(llvm::IntEQ, discr.immediate(), llval);
                        bx.cond_br(cmp, lltrue, llfalse);
                    }
                } else {
                    let (otherwise, targets) = targets.split_last().unwrap();
                    let switch = bx.switch(discr.immediate(),
                                            llblock(self, *otherwise), values.len());
                    let switch_llty = bx.cx.layout_of(switch_ty).immediate_llvm_type(bx.cx);
                    for (&value, target) in values.iter().zip(targets) {
                        let llval = C_uint_big(switch_llty, value);
                        let llbb = llblock(self, *target);
                        bx.add_case(switch, llval, llbb)
                    }
                }
            }

            mir::TerminatorKind::Return => {
                let llval = match self.fn_ty.ret.mode {
                    PassMode::Ignore | PassMode::Indirect(..) => {
                        bx.ret_void();
                        return;
                    }

                    PassMode::Direct(_) | PassMode::Pair(..) => {
                        let op = self.codegen_consume(&bx, &mir::Place::Local(mir::RETURN_PLACE));
                        if let Ref(llval, _, align) = op.val {
                            bx.load(llval, align)
                        } else {
                            op.immediate_or_packed_pair(&bx)
                        }
                    }

                    PassMode::Cast(cast_ty) => {
                        let op = match self.locals[mir::RETURN_PLACE] {
                            LocalRef::Operand(Some(op)) => op,
                            LocalRef::Operand(None) => bug!("use of return before def"),
                            LocalRef::Place(cg_place) => {
                                OperandRef {
                                    val: Ref(cg_place.llval, None, cg_place.align),
                                    layout: cg_place.layout
                                }
                            }
                            LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
                        };
                        let llslot = match op.val {
                            Immediate(_) | Pair(..) => {
                                let scratch = PlaceRef::alloca(&bx, self.fn_ty.ret.layout, "ret");
                                op.val.store(&bx, scratch);
                                scratch.llval
                            }
                            Ref(llval, _, align) => {
                                assert_eq!(align.abi(), op.layout.align.abi(),
                                           "return place is unaligned!");
                                llval
                            }
                        };
                        bx.load(
                            bx.pointercast(llslot, cast_ty.llvm_type(bx.cx).ptr_to()),
                            self.fn_ty.ret.layout.align)
                    }
                };
                bx.ret(llval);
            }

            mir::TerminatorKind::Unreachable => {
                bx.unreachable();
            }

            mir::TerminatorKind::Drop { ref location, target, unwind } => {
                let ty = location.ty(self.mir, bx.tcx()).to_ty(bx.tcx());
                let ty = self.monomorphize(&ty);
                let drop_fn = monomorphize::resolve_drop_in_place(bx.cx.tcx, ty);

                if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
                    // we don't actually need to drop anything.
                    funclet_br(self, bx, target);
                    return
                }

                let place = self.codegen_place(&bx, location);
                let (args1, args2);
                let mut args = if let Some(llextra) = place.llextra {
                    args2 = [place.llval, llextra];
                    &args2[..]
                } else {
                    args1 = [place.llval];
                    &args1[..]
                };
                let (drop_fn, fn_ty) = match ty.sty {
                    ty::Dynamic(..) => {
                        let fn_ty = drop_fn.ty(bx.cx.tcx);
                        let sig = common::ty_fn_sig(bx.cx, fn_ty);
                        let sig = bx.tcx().normalize_erasing_late_bound_regions(
                            ty::ParamEnv::reveal_all(),
                            &sig,
                        );
                        let fn_ty = FnType::new_vtable(bx.cx, sig, &[]);
                        let vtable = args[1];
                        args = &args[..1];
                        (meth::DESTRUCTOR.get_fn(&bx, vtable, &fn_ty), fn_ty)
                    }
                    _ => {
                        (callee::get_fn(bx.cx, drop_fn),
                         FnType::of_instance(bx.cx, &drop_fn))
                    }
                };
                do_call(self, bx, fn_ty, drop_fn, args,
                        Some((ReturnDest::Nothing, target)),
                        unwind);
            }

            mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
                let cond = self.codegen_operand(&bx, cond).immediate();
                let mut const_cond = common::const_to_opt_u128(cond, false).map(|c| c == 1);

                // This case can currently arise only from functions marked
                // with #[rustc_inherit_overflow_checks] and inlined from
                // another crate (mostly core::num generic/#[inline] fns),
                // while the current crate doesn't use overflow checks.
                // NOTE: Unlike binops, negation doesn't have its own
                // checked operation, just a comparison with the minimum
                // value, so we have to check for the assert message.
                if !bx.cx.check_overflow {
                    if let mir::interpret::EvalErrorKind::OverflowNeg = *msg {
                        const_cond = Some(expected);
                    }
                }

                // Don't codegen the panic block if success if known.
                if const_cond == Some(expected) {
                    funclet_br(self, bx, target);
                    return;
                }

                // Pass the condition through llvm.expect for branch hinting.
                let expect = bx.cx.get_intrinsic(&"llvm.expect.i1");
                let cond = bx.call(expect, &[cond, C_bool(bx.cx, expected)], None);

                // Create the failure block and the conditional branch to it.
                let lltarget = llblock(self, target);
                let panic_block = self.new_block("panic");
                if expected {
                    bx.cond_br(cond, lltarget, panic_block.llbb());
                } else {
                    bx.cond_br(cond, panic_block.llbb(), lltarget);
                }

                // After this point, bx is the block for the call to panic.
                bx = panic_block;
                self.set_debug_loc(&bx, terminator.source_info);

                // Get the location information.
                let loc = bx.sess().source_map().lookup_char_pos(span.lo());
                let filename = Symbol::intern(&loc.file.name.to_string()).as_str();
                let filename = C_str_slice(bx.cx, filename);
                let line = C_u32(bx.cx, loc.line as u32);
                let col = C_u32(bx.cx, loc.col.to_usize() as u32 + 1);
                let align = tcx.data_layout.aggregate_align
                    .max(tcx.data_layout.i32_align)
                    .max(tcx.data_layout.pointer_align);

                // Put together the arguments to the panic entry point.
                let (lang_item, args) = match *msg {
                    EvalErrorKind::BoundsCheck { ref len, ref index } => {
                        let len = self.codegen_operand(&mut bx, len).immediate();
                        let index = self.codegen_operand(&mut bx, index).immediate();

                        let file_line_col = C_struct(bx.cx, &[filename, line, col], false);
                        let file_line_col = consts::addr_of(bx.cx,
                                                            file_line_col,
                                                            align,
                                                            Some("panic_bounds_check_loc"));
                        (lang_items::PanicBoundsCheckFnLangItem,
                         vec![file_line_col, index, len])
                    }
                    _ => {
                        let str = msg.description();
                        let msg_str = Symbol::intern(str).as_str();
                        let msg_str = C_str_slice(bx.cx, msg_str);
                        let msg_file_line_col = C_struct(bx.cx,
                                                     &[msg_str, filename, line, col],
                                                     false);
                        let msg_file_line_col = consts::addr_of(bx.cx,
                                                                msg_file_line_col,
                                                                align,
                                                                Some("panic_loc"));
                        (lang_items::PanicFnLangItem,
                         vec![msg_file_line_col])
                    }
                };

                // Obtain the panic entry point.
                let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
                let instance = ty::Instance::mono(bx.tcx(), def_id);
                let fn_ty = FnType::of_instance(bx.cx, &instance);
                let llfn = callee::get_fn(bx.cx, instance);

                // Codegen the actual panic invoke/call.
                do_call(self, bx, fn_ty, llfn, &args, None, cleanup);
            }

            mir::TerminatorKind::DropAndReplace { .. } => {
                bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
            }

            mir::TerminatorKind::Call { ref func, ref args, ref destination, cleanup } => {
                // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
                let callee = self.codegen_operand(&bx, func);

                let (instance, mut llfn) = match callee.layout.ty.sty {
                    ty::FnDef(def_id, substs) => {
                        (Some(ty::Instance::resolve(bx.cx.tcx,
                                                    ty::ParamEnv::reveal_all(),
                                                    def_id,
                                                    substs).unwrap()),
                         None)
                    }
                    ty::FnPtr(_) => {
                        (None, Some(callee.immediate()))
                    }
                    _ => bug!("{} is not callable", callee.layout.ty)
                };
                let def = instance.map(|i| i.def);
                let sig = callee.layout.ty.fn_sig(bx.tcx());
                let sig = bx.tcx().normalize_erasing_late_bound_regions(
                    ty::ParamEnv::reveal_all(),
                    &sig,
                );
                let abi = sig.abi;

                // Handle intrinsics old codegen wants Expr's for, ourselves.
                let intrinsic = match def {
                    Some(ty::InstanceDef::Intrinsic(def_id))
                        => Some(bx.tcx().item_name(def_id).as_str()),
                    _ => None
                };
                let intrinsic = intrinsic.as_ref().map(|s| &s[..]);

                if intrinsic == Some("transmute") {
                    if let Some(destination_ref) = destination.as_ref() {
                        let &(ref dest, target) = destination_ref;
                        self.codegen_transmute(&bx, &args[0], dest);
                        funclet_br(self, bx, target);
                    } else {
                        // If we are trying to transmute to an uninhabited type,
                        // it is likely there is no allotted destination. In fact,
                        // transmuting to an uninhabited type is UB, which means
                        // we can do what we like. Here, we declare that transmuting
                        // into an uninhabited type is impossible, so anything following
                        // it must be unreachable.
                        assert_eq!(bx.cx.layout_of(sig.output()).abi, layout::Abi::Uninhabited);
                        bx.unreachable();
                    }
                    return;
                }

                if (intrinsic == Some("init") || intrinsic == Some("uninit")) &&
                    bx.cx.layout_of(sig.output()).abi.is_uninhabited()
                {
                    let loc = bx.sess().codemap().lookup_char_pos(span.lo());
                    let filename = Symbol::intern(&loc.file.name.to_string()).as_str();
                    let filename = C_str_slice(bx.cx, filename);
                    let line = C_u32(bx.cx, loc.line as u32);
                    let col = C_u32(bx.cx, loc.col.to_usize() as u32 + 1);
                    let align = tcx.data_layout.aggregate_align
                        .max(tcx.data_layout.i32_align)
                        .max(tcx.data_layout.pointer_align);

                    let str = format!(
                        "Attempted to instantiate uninhabited type {} using mem::{}",
                        sig.output(),
                        if intrinsic == Some("init") { "zeroed" } else { "uninitialized" }
                    );
                    let msg_str = Symbol::intern(&str).as_str();
                    let msg_str = C_str_slice(bx.cx, msg_str);
                    let msg_file_line_col = C_struct(bx.cx,
                                                    &[msg_str, filename, line, col],
                                                    false);
                    let msg_file_line_col = consts::addr_of(bx.cx,
                                                            msg_file_line_col,
                                                            align,
                                                            Some("panic_loc"));

                    // Obtain the panic entry point.
                    let def_id =
                        common::langcall(bx.tcx(), Some(span), "", lang_items::PanicFnLangItem);
                    let instance = ty::Instance::mono(bx.tcx(), def_id);
                    let fn_ty = FnType::of_instance(bx.cx, &instance);
                    let llfn = callee::get_fn(bx.cx, instance);

                    // Codegen the actual panic invoke/call.
                    do_call(
                        self,
                        bx,
                        fn_ty,
                        llfn,
                        &[msg_file_line_col],
                        destination.as_ref().map(|(_, bb)| (ReturnDest::Nothing, *bb)),
                        cleanup,
                    );
                    return;
                }

                let extra_args = &args[sig.inputs().len()..];
                let extra_args = extra_args.iter().map(|op_arg| {
                    let op_ty = op_arg.ty(self.mir, bx.tcx());
                    self.monomorphize(&op_ty)
                }).collect::<Vec<_>>();

                let fn_ty = match def {
                    Some(ty::InstanceDef::Virtual(..)) => {
                        FnType::new_vtable(bx.cx, sig, &extra_args)
                    }
                    Some(ty::InstanceDef::DropGlue(_, None)) => {
                        // empty drop glue - a nop.
                        let &(_, target) = destination.as_ref().unwrap();
                        funclet_br(self, bx, target);
                        return;
                    }
                    _ => FnType::new(bx.cx, sig, &extra_args)
                };

                // The arguments we'll be passing. Plus one to account for outptr, if used.
                let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
                let mut llargs = Vec::with_capacity(arg_count);

                // Prepare the return value destination<commit_msg>move our check to reuse a previous computation<commit_after>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use llvm::{self, BasicBlock};
use rustc::middle::lang_items;
use rustc::ty::{self, Ty, TypeFoldable};
use rustc::ty::layout::{self, LayoutOf};
use rustc::mir;
use rustc::mir::interpret::EvalErrorKind;
use abi::{Abi, ArgType, ArgTypeExt, FnType, FnTypeExt, LlvmType, PassMode};
use base;
use callee;
use builder::{Builder, MemFlags};
use common::{self, C_bool, C_str_slice, C_struct, C_u32, C_uint_big, C_undef};
use consts;
use meth;
use monomorphize;
use type_of::LayoutLlvmExt;
use type_::Type;
use value::Value;

use syntax::symbol::Symbol;
use syntax_pos::Pos;

use super::{FunctionCx, LocalRef};
use super::place::PlaceRef;
use super::operand::OperandRef;
use super::operand::OperandValue::{Pair, Ref, Immediate};

impl FunctionCx<'a, 'll, 'tcx> {
    pub fn codegen_block(&mut self, bb: mir::BasicBlock) {
        let mut bx = self.build_block(bb);
        let data = &self.mir[bb];

        debug!("codegen_block({:?}={:?})", bb, data);

        for statement in &data.statements {
            bx = self.codegen_statement(bx, statement);
        }

        self.codegen_terminator(bx, bb, data.terminator());
    }

    fn codegen_terminator(&mut self,
                        mut bx: Builder<'a, 'll, 'tcx>,
                        bb: mir::BasicBlock,
                        terminator: &mir::Terminator<'tcx>)
    {
        debug!("codegen_terminator: {:?}", terminator);

        // Create the cleanup bundle, if needed.
        let tcx = bx.tcx();
        let span = terminator.source_info.span;
        let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
        let funclet = funclet_bb.and_then(|funclet_bb| self.funclets[funclet_bb].as_ref());

        let cleanup_pad = funclet.map(|lp| lp.cleanuppad());
        let cleanup_bundle = funclet.map(|l| l.bundle());

        let lltarget = |this: &mut Self, target: mir::BasicBlock| {
            let lltarget = this.blocks[target];
            let target_funclet = this.cleanup_kinds[target].funclet_bb(target);
            match (funclet_bb, target_funclet) {
                (None, None) => (lltarget, false),
                (Some(f), Some(t_f))
                    if f == t_f || !base::wants_msvc_seh(tcx.sess)
                    => (lltarget, false),
                (None, Some(_)) => {
                    // jump *into* cleanup - need a landing pad if GNU
                    (this.landing_pad_to(target), false)
                }
                (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", terminator),
                (Some(_), Some(_)) => {
                    (this.landing_pad_to(target), true)
                }
            }
        };

        let llblock = |this: &mut Self, target: mir::BasicBlock| {
            let (lltarget, is_cleanupret) = lltarget(this, target);
            if is_cleanupret {
                // MSVC cross-funclet jump - need a trampoline

                debug!("llblock: creating cleanup trampoline for {:?}", target);
                let name = &format!("{:?}_cleanup_trampoline_{:?}", bb, target);
                let trampoline = this.new_block(name);
                trampoline.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
                trampoline.llbb()
            } else {
                lltarget
            }
        };

        let funclet_br = |this: &mut Self, bx: Builder<'_, 'll, '_>, target: mir::BasicBlock| {
            let (lltarget, is_cleanupret) = lltarget(this, target);
            if is_cleanupret {
                // micro-optimization: generate a `ret` rather than a jump
                // to a trampoline.
                bx.cleanup_ret(cleanup_pad.unwrap(), Some(lltarget));
            } else {
                bx.br(lltarget);
            }
        };

        let do_call = |
            this: &mut Self,
            bx: Builder<'a, 'll, 'tcx>,
            fn_ty: FnType<'tcx, Ty<'tcx>>,
            fn_ptr: &'ll Value,
            llargs: &[&'ll Value],
            destination: Option<(ReturnDest<'ll, 'tcx>, mir::BasicBlock)>,
            cleanup: Option<mir::BasicBlock>
        | {
            if let Some(cleanup) = cleanup {
                let ret_bx = if let Some((_, target)) = destination {
                    this.blocks[target]
                } else {
                    this.unreachable_block()
                };
                let invokeret = bx.invoke(fn_ptr,
                                           &llargs,
                                           ret_bx,
                                           llblock(this, cleanup),
                                           cleanup_bundle);
                fn_ty.apply_attrs_callsite(&bx, invokeret);

                if let Some((ret_dest, target)) = destination {
                    let ret_bx = this.build_block(target);
                    this.set_debug_loc(&ret_bx, terminator.source_info);
                    this.store_return(&ret_bx, ret_dest, &fn_ty.ret, invokeret);
                }
            } else {
                let llret = bx.call(fn_ptr, &llargs, cleanup_bundle);
                fn_ty.apply_attrs_callsite(&bx, llret);
                if this.mir[bb].is_cleanup {
                    // Cleanup is always the cold path. Don't inline
                    // drop glue. Also, when there is a deeply-nested
                    // struct, there are "symmetry" issues that cause
                    // exponential inlining - see issue #41696.
                    llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret);
                }

                if let Some((ret_dest, target)) = destination {
                    this.store_return(&bx, ret_dest, &fn_ty.ret, llret);
                    funclet_br(this, bx, target);
                } else {
                    bx.unreachable();
                }
            }
        };

        self.set_debug_loc(&bx, terminator.source_info);
        match terminator.kind {
            mir::TerminatorKind::Resume => {
                if let Some(cleanup_pad) = cleanup_pad {
                    bx.cleanup_ret(cleanup_pad, None);
                } else {
                    let slot = self.get_personality_slot(&bx);
                    let lp0 = slot.project_field(&bx, 0).load(&bx).immediate();
                    let lp1 = slot.project_field(&bx, 1).load(&bx).immediate();
                    slot.storage_dead(&bx);

                    if !bx.sess().target.target.options.custom_unwind_resume {
                        let mut lp = C_undef(self.landing_pad_type());
                        lp = bx.insert_value(lp, lp0, 0);
                        lp = bx.insert_value(lp, lp1, 1);
                        bx.resume(lp);
                    } else {
                        bx.call(bx.cx.eh_unwind_resume(), &[lp0], cleanup_bundle);
                        bx.unreachable();
                    }
                }
            }

            mir::TerminatorKind::Abort => {
                // Call core::intrinsics::abort()
                let fnname = bx.cx.get_intrinsic(&("llvm.trap"));
                bx.call(fnname, &[], None);
                bx.unreachable();
            }

            mir::TerminatorKind::Goto { target } => {
                funclet_br(self, bx, target);
            }

            mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
                let discr = self.codegen_operand(&bx, discr);
                if targets.len() == 2 {
                    // If there are two targets, emit br instead of switch
                    let lltrue = llblock(self, targets[0]);
                    let llfalse = llblock(self, targets[1]);
                    if switch_ty == bx.tcx().types.bool {
                        // Don't generate trivial icmps when switching on bool
                        if let [0] = values[..] {
                            bx.cond_br(discr.immediate(), llfalse, lltrue);
                        } else {
                            assert_eq!(&values[..], &[1]);
                            bx.cond_br(discr.immediate(), lltrue, llfalse);
                        }
                    } else {
                        let switch_llty = bx.cx.layout_of(switch_ty).immediate_llvm_type(bx.cx);
                        let llval = C_uint_big(switch_llty, values[0]);
                        let cmp = bx.icmp(llvm::IntEQ, discr.immediate(), llval);
                        bx.cond_br(cmp, lltrue, llfalse);
                    }
                } else {
                    let (otherwise, targets) = targets.split_last().unwrap();
                    let switch = bx.switch(discr.immediate(),
                                            llblock(self, *otherwise), values.len());
                    let switch_llty = bx.cx.layout_of(switch_ty).immediate_llvm_type(bx.cx);
                    for (&value, target) in values.iter().zip(targets) {
                        let llval = C_uint_big(switch_llty, value);
                        let llbb = llblock(self, *target);
                        bx.add_case(switch, llval, llbb)
                    }
                }
            }

            mir::TerminatorKind::Return => {
                let llval = match self.fn_ty.ret.mode {
                    PassMode::Ignore | PassMode::Indirect(..) => {
                        bx.ret_void();
                        return;
                    }

                    PassMode::Direct(_) | PassMode::Pair(..) => {
                        let op = self.codegen_consume(&bx, &mir::Place::Local(mir::RETURN_PLACE));
                        if let Ref(llval, _, align) = op.val {
                            bx.load(llval, align)
                        } else {
                            op.immediate_or_packed_pair(&bx)
                        }
                    }

                    PassMode::Cast(cast_ty) => {
                        let op = match self.locals[mir::RETURN_PLACE] {
                            LocalRef::Operand(Some(op)) => op,
                            LocalRef::Operand(None) => bug!("use of return before def"),
                            LocalRef::Place(cg_place) => {
                                OperandRef {
                                    val: Ref(cg_place.llval, None, cg_place.align),
                                    layout: cg_place.layout
                                }
                            }
                            LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
                        };
                        let llslot = match op.val {
                            Immediate(_) | Pair(..) => {
                                let scratch = PlaceRef::alloca(&bx, self.fn_ty.ret.layout, "ret");
                                op.val.store(&bx, scratch);
                                scratch.llval
                            }
                            Ref(llval, _, align) => {
                                assert_eq!(align.abi(), op.layout.align.abi(),
                                           "return place is unaligned!");
                                llval
                            }
                        };
                        bx.load(
                            bx.pointercast(llslot, cast_ty.llvm_type(bx.cx).ptr_to()),
                            self.fn_ty.ret.layout.align)
                    }
                };
                bx.ret(llval);
            }

            mir::TerminatorKind::Unreachable => {
                bx.unreachable();
            }

            mir::TerminatorKind::Drop { ref location, target, unwind } => {
                let ty = location.ty(self.mir, bx.tcx()).to_ty(bx.tcx());
                let ty = self.monomorphize(&ty);
                let drop_fn = monomorphize::resolve_drop_in_place(bx.cx.tcx, ty);

                if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
                    // we don't actually need to drop anything.
                    funclet_br(self, bx, target);
                    return
                }

                let place = self.codegen_place(&bx, location);
                let (args1, args2);
                let mut args = if let Some(llextra) = place.llextra {
                    args2 = [place.llval, llextra];
                    &args2[..]
                } else {
                    args1 = [place.llval];
                    &args1[..]
                };
                let (drop_fn, fn_ty) = match ty.sty {
                    ty::Dynamic(..) => {
                        let fn_ty = drop_fn.ty(bx.cx.tcx);
                        let sig = common::ty_fn_sig(bx.cx, fn_ty);
                        let sig = bx.tcx().normalize_erasing_late_bound_regions(
                            ty::ParamEnv::reveal_all(),
                            &sig,
                        );
                        let fn_ty = FnType::new_vtable(bx.cx, sig, &[]);
                        let vtable = args[1];
                        args = &args[..1];
                        (meth::DESTRUCTOR.get_fn(&bx, vtable, &fn_ty), fn_ty)
                    }
                    _ => {
                        (callee::get_fn(bx.cx, drop_fn),
                         FnType::of_instance(bx.cx, &drop_fn))
                    }
                };
                do_call(self, bx, fn_ty, drop_fn, args,
                        Some((ReturnDest::Nothing, target)),
                        unwind);
            }

            mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
                let cond = self.codegen_operand(&bx, cond).immediate();
                let mut const_cond = common::const_to_opt_u128(cond, false).map(|c| c == 1);

                // This case can currently arise only from functions marked
                // with #[rustc_inherit_overflow_checks] and inlined from
                // another crate (mostly core::num generic/#[inline] fns),
                // while the current crate doesn't use overflow checks.
                // NOTE: Unlike binops, negation doesn't have its own
                // checked operation, just a comparison with the minimum
                // value, so we have to check for the assert message.
                if !bx.cx.check_overflow {
                    if let mir::interpret::EvalErrorKind::OverflowNeg = *msg {
                        const_cond = Some(expected);
                    }
                }

                // Don't codegen the panic block if success if known.
                if const_cond == Some(expected) {
                    funclet_br(self, bx, target);
                    return;
                }

                // Pass the condition through llvm.expect for branch hinting.
                let expect = bx.cx.get_intrinsic(&"llvm.expect.i1");
                let cond = bx.call(expect, &[cond, C_bool(bx.cx, expected)], None);

                // Create the failure block and the conditional branch to it.
                let lltarget = llblock(self, target);
                let panic_block = self.new_block("panic");
                if expected {
                    bx.cond_br(cond, lltarget, panic_block.llbb());
                } else {
                    bx.cond_br(cond, panic_block.llbb(), lltarget);
                }

                // After this point, bx is the block for the call to panic.
                bx = panic_block;
                self.set_debug_loc(&bx, terminator.source_info);

                // Get the location information.
                let loc = bx.sess().source_map().lookup_char_pos(span.lo());
                let filename = Symbol::intern(&loc.file.name.to_string()).as_str();
                let filename = C_str_slice(bx.cx, filename);
                let line = C_u32(bx.cx, loc.line as u32);
                let col = C_u32(bx.cx, loc.col.to_usize() as u32 + 1);
                let align = tcx.data_layout.aggregate_align
                    .max(tcx.data_layout.i32_align)
                    .max(tcx.data_layout.pointer_align);

                // Put together the arguments to the panic entry point.
                let (lang_item, args) = match *msg {
                    EvalErrorKind::BoundsCheck { ref len, ref index } => {
                        let len = self.codegen_operand(&mut bx, len).immediate();
                        let index = self.codegen_operand(&mut bx, index).immediate();

                        let file_line_col = C_struct(bx.cx, &[filename, line, col], false);
                        let file_line_col = consts::addr_of(bx.cx,
                                                            file_line_col,
                                                            align,
                                                            Some("panic_bounds_check_loc"));
                        (lang_items::PanicBoundsCheckFnLangItem,
                         vec![file_line_col, index, len])
                    }
                    _ => {
                        let str = msg.description();
                        let msg_str = Symbol::intern(str).as_str();
                        let msg_str = C_str_slice(bx.cx, msg_str);
                        let msg_file_line_col = C_struct(bx.cx,
                                                     &[msg_str, filename, line, col],
                                                     false);
                        let msg_file_line_col = consts::addr_of(bx.cx,
                                                                msg_file_line_col,
                                                                align,
                                                                Some("panic_loc"));
                        (lang_items::PanicFnLangItem,
                         vec![msg_file_line_col])
                    }
                };

                // Obtain the panic entry point.
                let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
                let instance = ty::Instance::mono(bx.tcx(), def_id);
                let fn_ty = FnType::of_instance(bx.cx, &instance);
                let llfn = callee::get_fn(bx.cx, instance);

                // Codegen the actual panic invoke/call.
                do_call(self, bx, fn_ty, llfn, &args, None, cleanup);
            }

            mir::TerminatorKind::DropAndReplace { .. } => {
                bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
            }

            mir::TerminatorKind::Call { ref func, ref args, ref destination, cleanup } => {
                // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
                let callee = self.codegen_operand(&bx, func);

                let (instance, mut llfn) = match callee.layout.ty.sty {
                    ty::FnDef(def_id, substs) => {
                        (Some(ty::Instance::resolve(bx.cx.tcx,
                                                    ty::ParamEnv::reveal_all(),
                                                    def_id,
                                                    substs).unwrap()),
                         None)
                    }
                    ty::FnPtr(_) => {
                        (None, Some(callee.immediate()))
                    }
                    _ => bug!("{} is not callable", callee.layout.ty)
                };
                let def = instance.map(|i| i.def);
                let sig = callee.layout.ty.fn_sig(bx.tcx());
                let sig = bx.tcx().normalize_erasing_late_bound_regions(
                    ty::ParamEnv::reveal_all(),
                    &sig,
                );
                let abi = sig.abi;

                // Handle intrinsics old codegen wants Expr's for, ourselves.
                let intrinsic = match def {
                    Some(ty::InstanceDef::Intrinsic(def_id))
                        => Some(bx.tcx().item_name(def_id).as_str()),
                    _ => None
                };
                let intrinsic = intrinsic.as_ref().map(|s| &s[..]);

                if intrinsic == Some("transmute") {
                    if let Some(destination_ref) = destination.as_ref() {
                        let &(ref dest, target) = destination_ref;
                        self.codegen_transmute(&bx, &args[0], dest);
                        funclet_br(self, bx, target);
                    } else {
                        // If we are trying to transmute to an uninhabited type,
                        // it is likely there is no allotted destination. In fact,
                        // transmuting to an uninhabited type is UB, which means
                        // we can do what we like. Here, we declare that transmuting
                        // into an uninhabited type is impossible, so anything following
                        // it must be unreachable.
                        assert_eq!(bx.cx.layout_of(sig.output()).abi, layout::Abi::Uninhabited);
                        bx.unreachable();
                    }
                    return;
                }

                let extra_args = &args[sig.inputs().len()..];
                let extra_args = extra_args.iter().map(|op_arg| {
                    let op_ty = op_arg.ty(self.mir, bx.tcx());
                    self.monomorphize(&op_ty)
                }).collect::<Vec<_>>();

                let fn_ty = match def {
                    Some(ty::InstanceDef::Virtual(..)) => {
                        FnType::new_vtable(bx.cx, sig, &extra_args)
                    }
                    Some(ty::InstanceDef::DropGlue(_, None)) => {
                        // empty drop glue - a nop.
                        let &(_, target) = destination.as_ref().unwrap();
                        funclet_br(self, bx, target);
                        return;
                    }
                    _ => FnType::new(bx.cx, sig, &extra_args)
                };

                // emit a panic instead of instantiating an uninhabited type
                if (intrinsic == Some("init") || intrinsic == Some("uninit")) &&
                    fn_ty.ret.layout.abi.is_uninhabited()
                {
                    let loc = bx.sess().codemap().lookup_char_pos(span.lo());
                    let filename = Symbol::intern(&loc.file.name.to_string()).as_str();
                    let filename = C_str_slice(bx.cx, filename);
                    let line = C_u32(bx.cx, loc.line as u32);
                    let col = C_u32(bx.cx, loc.col.to_usize() as u32 + 1);
                    let align = tcx.data_layout.aggregate_align
                        .max(tcx.data_layout.i32_align)
                        .max(tcx.data_layout.pointer_align);

                    let str = format!(
                        "Attempted to instantiate uninhabited type {} using mem::{}",
                        sig.output(),
                        if intrinsic == Some("init") { "zeroed" } else { "uninitialized" }
                    );
                    let msg_str = Symbol::intern(&str).as_str();
                    let msg_str = C_str_slice(bx.cx, msg_str);
                    let msg_file_line_col = C_struct(bx.cx,
                                                    &[msg_str, filename, line, col],
                                                    false);
                    let msg_file_line_col = consts::addr_of(bx.cx,
                                                            msg_file_line_col,
                                                            align,
                                                            Some("panic_loc"));

                    // Obtain the panic entry point.
                    let def_id =
                        common::langcall(bx.tcx(), Some(span), "", lang_items::PanicFnLangItem);
                    let instance = ty::Instance::mono(bx.tcx(), def_id);
                    let fn_ty = FnType::of_instance(bx.cx, &instance);
                    let llfn = callee::get_fn(bx.cx, instance);

                    // Codegen the actual panic invoke/call.
                    do_call(
                        self,
                        bx,
                        fn_ty,
                        llfn,
                        &[msg_file_line_col],
                        destination.as_ref().map(|(_, bb)| (ReturnDest::Nothing, *bb)),
                        cleanup,
                    );
                    return;
                }

                // The arguments we'll be passing. Plus one to account for outptr, if used.
                let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
                let mut llargs = Vec::with_capacity(arg_count);

                // Prepare the return value destination
{'fraction_non_alphanumeric': 0.1109127338372116, 'fraction_numerical': 0.002777281834593029, 'mean_word_length': 1.182345556084679, 'pattern_counts': {'":': 0, '<': 31, '<?xml version=': 0, '>': 103, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 100, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5922253', 'n_tokens_mistral': 13796, 'n_tokens_neox': 12809, 'n_words': 2829}