text:
package service

import scalikejdbc._, SQLInterpolation._
import skinny.dbmigration.DBSeeds

trait CreateTables extends DBSeeds { self: Connection =>

  override val dbSeedsAutoSession = NamedAutoSession('service)

  addSeedSQL(
    sql"""
create table services (
  id bigint auto_increment primary key not null,
  name varchar(128) not null,
  created_at timestamp not null,
  updated_at timestamp not null,
  deleted_at timestamp
)
""",
    sql"""
create table applications (
  id bigint auto_increment primary key not null,
  name varchar(128) not null,
  service_id bigint not null references services(id),
  created_at timestamp not null,
  updated_at timestamp not null,
  deleted_at timestamp
)
""",
    sql"""
create table service_settings (
  id bigint auto_increment primary key not null,
  maximum_accounts bigint not null default 10000,
  service_id bigint not null references services(id),
  created_at timestamp not null,
  updated_at timestamp not null
)
"""
  )

  runIfFailed(sql"select count(1) from services")
}


text:
<?php

namespace Bixev\InterventionSdk\Model;

class Api
{

    use \Bixev\LightLogger\LoggerTrait;
    use \Bixev\InterventionSdk\Traits\ClientTrait;

    public function __construct($client = null, \Bixev\LightLogger\LoggerInterface $logger = null)
    {
        $this->setClient($client);
        $this->setLogger($logger);
    }

    public function newModelIntervention()
    {
        return new Intervention();
    }

    public function newModelCustomer()
    {
        return new Customer();
    }

}

redpajama_set_name: RedPajamaGithub


text:
require 'rails_helper'

RSpec.describe Letter, type: :model do
  let(:letter_template) { create(:letter_template, name: "Letter to Requester") }
  let(:kase) { create(:offender_sar_case, name: 'Waylon Smithers', subject_address: 'address') }

  it 'can be created' do
    letter = Letter.new 1
    expect(letter.letter_template_id).to eq 1
  end

  it 'delegates values to a case' do
    letter = Letter.new(letter_template.id, kase)
    expect(letter.values.name).to eq "Waylon Smithers"
  end

  it 'renders a case' do
    letter = Letter.new(letter_template.id, kase)
    expect(letter.body).to eq 'Thank you for your offender subject access request, Waylon Smithers'
  end

  it 'renders a letter_address' do
    letter = Letter.new(letter_template.id, kase)
    expect(letter.letter_address).to eq 'Testing address'
  end

  it 'displays the template name' do
    letter = Letter.new(letter_template.id, kase)
    expect(letter.template_name).to eq 'Letter to Requester'
  end

  describe '#name' do
    context 'when letter template is acknowledgement letter' do
      context 'when subject is requester' do
        it 'returns the subject name' do
          letter = Letter.new(letter_template.id, kase)
          expect(letter.name).to eq kase.requester_name
          expect(letter.name).to eq kase.subject_name
        end
      end

      context 'when third party is requester' do
        let(:kase) { build(:offender_sar_case, :third_party, third_party_name: "Bob") }
        it 'returns the third_party name' do
          letter = Letter.new(letter_template.id, kase)
          expect(letter.name).to eq kase.requester_name
          expect(letter.name).to eq kase.third_party_name
        end
      end
    end

    context 'when letter template is dispatch letter' do
      let(:letter_template) { create(:letter_template, template_type: "dispatch", name: "Letter to Recipient") }

      context 'when subject is recipient' do
        it 'returns the subject name' do
          letter = Letter.new(letter_template.id, kase)
          expect(letter.name).to eq kase.recipient_name
          expect(letter.name).to eq kase.subject_name
        end
      end

      context 'when third party is recipient' do
        let(:kase) { build(:offender_sar_case, :third_party, third_party_name: "Bob") }

        it 'returns the third_party name' do
          letter = Letter.new(letter_template.id, kase)
          expect(letter.name).to eq kase.recipient_name
          expect(letter.name).to eq kase.third_party_name
        end
      end
    end
  end

  describe '#address' do
    context 'when letter template is acknowledgement letter' do
      context 'when subject is requester' do
        it 'returns the subject address' do
          letter = Letter.new(letter_template.id, kase)
          expect(letter.address).to eq kase.requester_address
          expect(letter.address).to eq kase.subject_address
        end
      end

      context 'when third party is requester' do
        let(:kase) { build(:offender_sar_case, :third_party, postal_address: "33 High Street") }
        it 'returns the third_party address' do
          letter = Letter.new(letter_template.id, kase)
          expect(letter.address).to eq kase.requester_address
          expect(letter.address).to eq kase.third_party_address
        end
      end
    end

    context 'when letter template is dispatch letter' do
      let(:letter_template) { create(:letter_template, template_type: "dispatch", name: "Letter to Recipient") }

      context 'when subject is recipient' do
        it 'returns the subject address' do
          letter = Letter.new(letter_template.id, kase)
          expect(letter.address).to eq kase.recipient_address
          expect(letter.address).to eq kase.subject_address
        end
      end

      context 'when third party is recipient' do
        let(:kase) { build(:offender_sar_case, :third_party, postal_address: "33 High Street") }

        it 'returns the third_party address' do
          letter = Letter.new(letter_template.id, kase)
          expect(letter.address).to eq kase.recipient_address
          expect(letter.address).to eq kase.third_party_address
        end
      end
    end
  end

  describe '#company_name' do
    context 'when no company_name is present' do
     let(:kase) { build(:offender_sar_case) }
      it 'returns nil' do
        letter = Letter.new(letter_template.id, kase)
        expect(letter.company_name).to be_nil
      end
    end

    context 'when company_name is blank' do
     let(:kase) { build(:offender_sar_case, :third_party, third_party_company_name: '') }
      it 'returns nil' do
        letter = Letter.new(letter_template.id, kase)
        expect(letter.company_name).to be_nil
      end
    end

    context 'when company_name is present' do
     let(:kase) { build(:offender_sar_case, :third_party, third_party_company_name: 'Wibble') }
      it 'returns the company name' do
        letter = Letter.new(letter_template.id, kase)
        expect(letter.company_name).to eq "Wibble"
      end
    end
  end

  describe '#format_address' do
    let(:kase_two) { create(:offender_sar_case, name: 'Waylon Smithers',
                        subject_address: '22 Sample Address, Test Lane, Testingington, TE57ST') }

    it 'formats address into new lines' do
      letter = Letter.new(letter_template.id, kase_two)
      address_with_newlines = letter.address
      expect(address_with_newlines).to eq "22 Sample Address\nTest Lane\nTestingington\nTE57ST"
    end
  end
end


text:
/* global define, window, document, app */
define([
	"map/Map"
], function (Map) {
	'use strict';
	/* Main Controller for the Map */

	var _map;

	return {

		init: function (options) {
			if (app.map) {
				return;
			}
			// Set Esri Map Object into Global namespace for easy access after creation
			_map = new Map(options);
			app.map = _map.map;

			_map.on('ready', this.mapLoaded);

		},

		mapLoaded: function () {

		}

	};

});


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.archanaiyer.hungrypenguin.ui.FoodDetailActivity"
    tools:showIn="@layout/activity_food_detail">

    <ImageView
        android:id="@+id/dish_image"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_alignParentTop="true"
        android:adjustViewBounds="true"
        android:paddingTop="20dp"
        android:src="@drawable/com_facebook_profile_picture_blank_square" />

    <LinearLayout
        android:id="@+id/linear2"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/dish_image"
        android:orientation="vertical">

        <TextView
            android:id="@+id/dish_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Dish 1"
            android:textSize="40dp"
            android:textStyle="bold" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@android:color/darker_gray" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@android:color/darker_gray" />

        <RatingBar
            android:id="@+id/rating_bar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_gravity="center"
            android:stepSize="0.5"
            android:layout_marginTop="20dp" />

        <TextView
            android:id="@+id/reviews"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Reviews"
            android:textSize="30dp"
            android:textStyle="bold" />

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:id="@+id/reviewList">

            </LinearLayout>
        </ScrollView>

        <!--<TextView-->
            <!--android:id="@+id/review1"-->
            <!--android:layout_width="match_parent"-->
            <!--android:layout_height="wrap_content"-->
            <!--android:layout_gravity="center"-->
            <!--android:layout_marginTop="10dp"-->
            <!--android:background="@drawable/back"-->
            <!--android:padding="15dp"-->
            <!--android:text="Wow this is great! -Anshima"-->
            <!--android:textSize="20dp" />-->

        <!--<TextView-->
            <!--android:id="@+id/review2"-->
            <!--android:layout_width="match_parent"-->
            <!--android:layout_height="wrap_content"-->
            <!--android:layout_gravity="center"-->
            <!--android:layout_marginTop="10dp"-->
            <!--android:background="@drawable/back"-->
            <!--android:padding="15dp"-->
            <!--android:text="I will eat this everyday! -Pappu"-->
            <!--android:textSize="20dp" />-->
    </LinearLayout>

</RelativeLayout>


text:
class IngredientFamiliesController < ApplicationController
  include CocktailsHelper
  before_action :set_ingredient_family, only: [:edit, :update, :destroy] #:show,
  before_action :set_ingredient_categories, only: [:new, :edit]

  # GET /ingredient_families
  # GET /ingredient_families.json
  def index
    @ingredient_families = IngredientFamily.all
  end

  # GET /ingredient_families/1
  # GET /ingredient_families/1.json
  def show
    @ingredient_family = IngredientFamily.#includes(:ingredient_types).
      find params[:id]
    get_active_filters params
    build_filter_hash params
    @filters = @filter_hash.values
    @filtered_cocktails = filtered_cocktails(@ingredient_family, @filter_hash)
    @filtered_shared_ingredients = Ingredient.new.filtered_shared_ingredients(@filtered_cocktails)
    @filtered_ingredient_types = IngredientType.new.filtered_ingredient_types(@filtered_cocktails)
    @filtered_ingredient_families = @ingredient_family.filtered_ingredient_families(@filtered_cocktails)
    @filtered_modifications = IngredientModification.filtered_modifications(@filtered_cocktails)
    @shared_ingredient_heirarchy = Ingredient.shared_ingredient_heirarchy @ingredient_family.ingredients, @filtered_cocktails
  end

  # GET /ingredient_families/new
  def new
    @ingredient_family = IngredientFamily.new
  end

  # GET /ingredient_families/1/edit
  def edit
  end

  # POST /ingredient_families
  # POST /ingredient_families.json
  def create
    @ingredient_family = IngredientFamily.new(ingredient_family_params)

    respond_to do |format|
      if @ingredient_family.save
        format.html { redirect_to @ingredient_family, notice: 'Ingredient family was successfully created.' }
        format.json { render action: 'show', status: :created, location: @ingredient_family }
      else
        format.html { render action: 'new' }
        format.json { render json: @ingredient_family.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /ingredient_families/1
  # PATCH/PUT /ingredient_families/1.json
  def update
    respond_to do |format|
      if @ingredient_family.update(ingredient_family_params)
        format.html { redirect_to @ingredient_family, notice: 'Ingredient family was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @ingredient_family.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /ingredient_families/1
  # DELETE /ingredient_families/1.json
  def destroy
    @ingredient_family.destroy
    respond_to do |format|
      format.html { redirect_to ingredient_families_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_ingredient_family
      @ingredient_family = IngredientFamily.find(params[:id])
    end

    def set_ingredient_categories
      @ingredient_categories = IngredientCategory.all
      @ingredient_category_dropdown = @ingredient_categories.map { |it| [it.name, it.id] }
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def ingredient_family_params
      params.require(:ingredient_family).permit(:name, :ingredient_category_id)
    end
end


text:
export const loadState = () => {
  try {
    const storedState = localStorage.getItem('state');
    return storedState ? JSON.parse(storedState) : {};
  } catch (e) {
    // eslint-disable-next-line
    console.error('could not load state', e);
    return {}
  }
};

export const saveState = (state) => {
  try {
    // only save some state properties
    localStorage.setItem('state', JSON.stringify(state));
  } catch (e) {
    // eslint-disable-next-line
    console.error('could not persist state', e);
  }
};

const parseRecentlyViewed = () => {
  const recentlyViewed = JSON.parse(localStorage.getItem('recentlyViewed'));

  return recentlyViewed || {};
}

export const setRecentlyViewedItem = (id) => {
  const recentlyViewed = parseRecentlyViewed();
  recentlyViewed[id] = Date.now();
  localStorage.setItem('recentlyViewed', JSON.stringify(recentlyViewed));
}

export const getRecentlyViewedItem = (id) => {
  const recentlyViewed = parseRecentlyViewed();
  const item = recentlyViewed[id];

  return item;
}

export const expireRecentlyViewed = () => {
  const recentlyViewed = parseRecentlyViewed();
  const expiry = 5259600000; // Two months
  const expiryDate = Date.now() - expiry;

  // Not wanting to prematurely optamise here but If
  // walking the entire list becomes an issue in the future
  // look to first sorting the list of recentlyViewed items
  // by date using recentlyViewed.entries() and then .sort()
  // you can then remove everying that is expired and stop before
  // iterating the entire list of entries.
  for(const item in recentlyViewed) {
    const itemDate = new Date(parseInt(recentlyViewed[item], 10));

    if(itemDate < expiryDate) {
      delete recentlyViewed[item];
    }
  }

  localStorage.setItem('recentlyViewed', JSON.stringify(recentlyViewed));
}

export const setSearchConfig = (searchConfig) => {
  localStorage.setItem('searchConfig', JSON.stringify(searchConfig));
}

export const getSearchConfig = () => {
  return JSON.parse(localStorage.getItem('searchConfig'));
}


text:
/*----------------------------------------------
Programmer: Alberto Bobadilla (labigm@gmail.com)
Date: 2015/06
----------------------------------------------*/
#ifndef __SHADERMANAGERSINGLETON_H_
#define __SHADERMANAGERSINGLETON_H_

#include "RE\system\ShaderClass.h"
#include <vector>
#include <assert.h>
#include <map>
namespace ReEng
{

//System Class
class ReEngDLL ShaderManagerSingleton
{
	int m_nShaders = 0; //Number of shaders

	static ShaderManagerSingleton* m_pInstance; // Singleton

	std::vector<ShaderClass> m_vShader; //vector of shaders
	std::map<String, int> m_map;//Indexer of Shaders

public:
	/* Singleton accessor */
	static ShaderManagerSingleton* GetInstance();

	/* Singleton Release */
	static void ReleaseInstance(void);

	/* Compiles a shader program and returns the OpenGL identifier */
	GLuint CompileShader(String a_sVertexShader, String a_sFragmentShader, String a_sName = "");

	/* Asks the manager for the OpenGL identifier for the specified name*/
	GLuint GetShaderID(String a_sName);

	/* Asks the manager for the OpenGL identifier for the specified index*/
	GLuint GetShaderID(int a_nIndex);

	/* Ask for the Index in the vector of the specified shader name*/
	int IdentifyShader(String a_sName);

private:
	/* Constructor */
	ShaderManagerSingleton(void);

	/* Copy Constructor */
	ShaderManagerSingleton(ShaderManagerSingleton const& other);

	/* Copy Assignment Operator */
	ShaderManagerSingleton& operator=(ShaderManagerSingleton const& other);

	/* Destructor */
	~ShaderManagerSingleton(void);

	/* Release Memory */
	void Release(void);

	/* Initialize variables */
	void Init(void);
};

}
#endif //__SHADERMANAGERSINGLETON_H_


text:
import React, {PureComponent, RefObject} from 'react'
import {
  Button,
  ComponentColor,
  ComponentSize,
  ButtonType,
  ComponentStatus,
} from '@influxdata/clockface'

interface Props {
  onClickBack?: () => void
  skipButtonText?: string
  nextButtonText?: string
  backButtonText?: string
  onClickSkip?: () => void
  nextButtonStatus?: ComponentStatus
  showSkip?: boolean
  autoFocusNext?: boolean
  className?: string
}

class OnboardingButtons extends PureComponent<Props> {
  public static defaultProps: Props = {
    nextButtonStatus: ComponentStatus.Default,
    showSkip: false,
    autoFocusNext: true,
    skipButtonText: 'Skip',
    backButtonText: 'Previous',
    nextButtonText: 'Continue',
  }

  private submitRef: RefObject<HTMLButtonElement> = React.createRef()

  public componentDidMount() {
    if (this.props.autoFocusNext) {
      const buttonRef = this.submitRef.current
      if (buttonRef) {
        buttonRef.focus()
      }
    }
  }

  public componentDidUpdate() {
    if (this.props.autoFocusNext) {
      const buttonRef = this.submitRef.current
      if (buttonRef) {
        buttonRef.focus()
      }
    }
  }

  public render() {
    const {nextButtonText, nextButtonStatus} = this.props
    return (

          {this.backButton}
          <Button
            color={ComponentColor.Primary}
            text={nextButtonText}
            size={ComponentSize.Medium}
            type={ButtonType.Submit}
            testID="next"
            refObject={this.submitRef}
            status={nextButtonStatus}
            tabIndex={0}
          />

        {this.skipButton}

    )
  }

  private get className(): string {
    return this.props.className || ''
  }

  private get backButton(): JSX.Element {
    const {backButtonText, onClickBack} = this.props

    if (!onClickBack || !backButtonText) {
      return
    }

    return (
      <Button
        color={ComponentColor.Default}
        text={backButtonText}
        size={ComponentSize.Medium}
        onClick={onClickBack}
        testID="back"
        tabIndex={1}
      />
    )
  }

  private get skipButton(): JSX.Element {
    const {skipButtonText, onClickSkip, showSkip} = this.props
    if (!showSkip) {
      return
    }

    return (

        <Button
          className="wizard--skip-button"
          size={ComponentSize.Medium}
          color={ComponentColor.Default}
          text={skipButtonText}
          onClick={onClickSkip}
          testID="skip"
        />

    )
  }
}

export default OnboardingButtons


text:
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.ExtractInterface;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.ExtractInterface
{
    [ExportLanguageService(typeof(AbstractExtractInterfaceService), LanguageNames.CSharp), Shared]
    internal sealed class CSharpExtractInterfaceService : AbstractExtractInterfaceService
    {
        internal override async Task<SyntaxNode> GetTypeDeclarationAsync(Document document, int position, TypeDiscoveryRule typeDiscoveryRule, CancellationToken cancellationToken)
        {
            var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
            var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
            var token = root.FindToken(position != tree.Length ? position : Math.Max(0, position - 1));
            var typeDeclaration = token.GetAncestor<TypeDeclarationSyntax>();

            if (typeDeclaration == null ||
                typeDiscoveryRule == TypeDiscoveryRule.TypeDeclaration)
            {
                return typeDeclaration;
            }

            var spanStart = typeDeclaration.Identifier.SpanStart;
            var spanEnd = typeDeclaration.TypeParameterList != null ? typeDeclaration.TypeParameterList.Span.End : typeDeclaration.Identifier.Span.End;
            var span = new TextSpan(spanStart, spanEnd - spanStart);

            return span.IntersectsWith(position) ? typeDeclaration : null;
        }

        internal override Solution GetSolutionWithUpdatedOriginalType(
            Solution solutionWithFormattedInterfaceDocument,
            INamedTypeSymbol extractedInterfaceSymbol,
            IEnumerable<ISymbol> includedMembers,
            Dictionary<ISymbol, SyntaxAnnotation> symbolToDeclarationAnnotationMap,
            List<DocumentId> documentIds,
            SyntaxAnnotation typeNodeAnnotation,
            DocumentId documentIdWithTypeNode,
            CancellationToken cancellationToken)
        {
            var documentWithTypeNode = solutionWithFormattedInterfaceDocument.GetDocument(documentIdWithTypeNode);
            var root = documentWithTypeNode.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
            var typeDeclaration = root.GetAnnotatedNodes<TypeDeclarationSyntax>(typeNodeAnnotation).Single();

            var docId = solutionWithFormattedInterfaceDocument.GetDocument(typeDeclaration.SyntaxTree).Id;

            var implementedInterfaceTypeSyntax = extractedInterfaceSymbol.TypeParameters.Any()
                ? SyntaxFactory.GenericName(
                    SyntaxFactory.Identifier(extractedInterfaceSymbol.Name),
                    SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(extractedInterfaceSymbol.TypeParameters.Select(p => SyntaxFactory.ParseTypeName(p.Name)))))
                : SyntaxFactory.ParseTypeName(extractedInterfaceSymbol.Name);

            var baseList = typeDeclaration.BaseList ?? SyntaxFactory.BaseList();
            var updatedBaseList = baseList.WithTypes(SyntaxFactory.SeparatedList(baseList.Types.Union(new[] { SyntaxFactory.SimpleBaseType(implementedInterfaceTypeSyntax) })));

            if (!baseList.Types.Any())
            {
                // If we're adding the first element to the base list, then we need to move
                // trivia from the type name itself to the end of the base list

                updatedBaseList = updatedBaseList.WithLeadingTrivia(SyntaxFactory.Space);

                if (typeDeclaration.TypeParameterList != null)
                {
                    updatedBaseList = updatedBaseList.WithTrailingTrivia(typeDeclaration.TypeParameterList.GetTrailingTrivia());
                    typeDeclaration = typeDeclaration.WithTypeParameterList(typeDeclaration.TypeParameterList.WithoutTrailingTrivia());
                }
                else
                {
                    updatedBaseList = updatedBaseList.WithTrailingTrivia(typeDeclaration.Identifier.TrailingTrivia);
                    typeDeclaration = typeDeclaration.WithIdentifier(typeDeclaration.Identifier.WithTrailingTrivia());
                }
            }

            var updatedTypeDeclaration = typeDeclaration.WithBaseList(updatedBaseList.WithAdditionalAnnotations(Formatter.Annotation));
            var updatedRoot = root.ReplaceNode(root.GetAnnotatedNodes<TypeDeclarationSyntax>(typeNodeAnnotation).Single(), updatedTypeDeclaration);
            var solutionWithOriginalTypeUpdated = solutionWithFormattedInterfaceDocument.WithDocumentSyntaxRoot(docId, updatedRoot, PreservationMode.PreserveIdentity);
            return solutionWithOriginalTypeUpdated;
        }

        internal override string GetGeneratedNameTypeParameterSuffix(IList<ITypeParameterSymbol> typeParameters, Workspace workspace)
        {
            if (typeParameters.IsEmpty())
            {
                return string.Empty;
            }

            var typeParameterList = SyntaxFactory.TypeParameterList(SyntaxFactory.SeparatedList(typeParameters.Select(p => SyntaxFactory.TypeParameter(p.Name))));
            return Formatter.Format(typeParameterList, workspace).ToString();
        }

        internal override string GetContainingNamespaceDisplay(INamedTypeSymbol typeSymbol, CompilationOptions compilationOptions)
        {
            return typeSymbol.ContainingNamespace.IsGlobalNamespace
                ? string.Empty
                : typeSymbol.ContainingNamespace.ToDisplayString();
        }

        internal override bool IsExtractableMember(ISymbol m)
        {
            return base.IsExtractableMember(m) && !m.ExplicitInterfaceImplementations().Any();
        }

        internal override bool ShouldIncludeAccessibilityModifier(SyntaxNode typeNode)
        {
            var typeDeclaration = typeNode as TypeDeclarationSyntax;
            return typeDeclaration.Modifiers.Any(m => SyntaxFacts.IsAccessibilityModifier(m.Kind()));
        }
    }
}


text:
% !TEX TS-program = pdflatex
% !TEX encoding = UTF-8 Unicode

\documentclass{beamer}

\mode<presentation> { }

\usepackage[english]{babel}

\usepackage[utf8]{inputenc}
\usepackage{xcolor}
\usepackage{listings}
\usepackage{lsthaskell}
\usepackage{times}
\usepackage[T1]{fontenc}
\usepackage{verbatim}
\usepackage{mathrsfs}
\usepackage{mathtools}
\usepackage{proof}
\usepackage{amscd}
\setbeamertemplate{frametitle}
  {\begin{centering}\smallskip
   \insertframetitle\par
   \smallskip\end{centering}}
\setbeamertemplate{itemize item}{$\bullet$}
\setbeamertemplate{navigation symbols}{}
\setbeamertemplate{footline}[text line]{%
    \hfill\strut{%
        \scriptsize\sf\color{black!60}%
        \quad\insertframenumber
    }%
    \hfill
}

\definecolor{ltblue}{rgb}{0,0.4,0.4}
\definecolor{dkblue}{rgb}{0,0.05,0.4}
\definecolor{dkgreen}{rgb}{0,0.35,0}
\definecolor{dkviolet}{rgb}{0.3,0,0.5}
\definecolor{dkred}{rgb}{0.5,0,0}
\definecolor{grey}{rgb}{0.5,0.5,0.6}
\usepackage{listings}
\lstset{
basicstyle=\footnotesize,
columns=fullflexible,
language=Haskell}

%settings
\everymath{\displaystyle}

%--------

\title[]{Different recursion schemas and their properties}

\author{I.Zhirkov}

\date{2015}
\subject{Theoretical Computer Science}

\newcommand{\hin}[2]{\lstinputlisting[firstline=#1, lastline=#2]{listings/algebra.hs}}

% Delete this, if you do not want the table of contents to pop up at
% the beginning of each subsection:
\AtBeginSubsection[]
{
  \begin{frame}<beamer>{Outline}
    \tableofcontents[currentsection,currentsubsection]
  \end{frame}
}

% If you wish to uncover everything in a step-wise fashion, uncomment
% the following command:

%\beamerdefaultoverlayspecification{<+->}

\begin{document}

\begin{frame}
  \titlepage
\end{frame}

%\begin{frame}{Outline}
%  \tableofcontents
%\end{frame}

\begin{frame}
\frametitle{Morphisms}
\begin{itemize}
    \item Catamorphisms (destruction)
    \item Anamorphisms (construction)
    \item Hylomorphisms (combination of two)
    \item Paramorphisms (saves more information than hylomorphisms)
\end{itemize}
\end{frame}

\section{Catamorphisms}

\begin{frame}{Catamorphism}
\begin{itemize}
\item ``generalized fold''

$b::B$

\begin{align*}
h::&\  \text{List}\ A \rightarrow B\\
\\
h\ Nil &= b\\
h\ (Cons \ a\ as) &=  f\ a\ (h\ as)
\end{align*}

~

\item Notation: $h = (\!|b, f|\!)$
\item Arises from algebra ($f\ a \rightarrow a$).
\end{itemize}

\end{frame}

\begin{frame}{Anamorphism}
\begin{itemize}
\item ``generalized unfold''

$p::\ B\rightarrow Bool$

$g:: B \rightarrow (A,B)$

~

\begin{align*}
h::&\  B \rightarrow List\ A\\
h\ b &= Nil, & p \ b \\
h\ b &=  Cons a\ (h\ b'),& otherwise
\end{align*}

where $(a,b') = g\ b $

\item Notation $h = [\!(g,p)\!]$
\item Arises from coalgebra ($a \rightarrow f\ a$).
\end{itemize}

\end{frame}

\begin{frame}{Hylomorphism}
\begin{itemize}
\item ``call-tree looks like data structure''

$c::\ C$

$f:: B\rightarrow C \rightarrow C$

$g:: A \rightarrow (B,A)$

$p:\ A\rightarrow Bool$

~

\begin{align*}
h::&\   A \rightarrow C\\
h\ a &= c, & p \ a \\
 &= f\ b (h\ a'), & otherwise
\end{align*}

where $(b, a') = g\ a$

\item Notation $h = [\![(c,f), (g,p)]\!]$
\end{itemize}

\end{frame}

\begin{frame}{Hylomorphism-2}
\begin{itemize}

\item Is a composition of anamorphism and catamorphism

$[\![(c,f), (g,p)]\!] = (\!|c, f|\!) \circ [\!(g, p)\!]$

\item \textit{Look at the whiteboard for a fancy call-tree image}
\item Example: factorial is $[\![(1, \times), (g,p)]\!]$, where:

\begin{align*}
p\ n &= n == 0 \\
g\ n &= (n, n-1)
\end{align*}
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Paramorphism}

\begin{itemize}
\item Hylomorphism for \textit{fac }is not inductively defined on \textit{nat}.
\item A nat paramorphism example:

\begin{align*}
h\ 0&= b\\
h\ (\text{Succ} \ n ) &= f\ n\ (h\ n)
\end{align*}

\item A list example:

\begin{align*}
h\ \text{Nil}& = b\\
h\ (\text{Cons}\ x\ xs ) &= f\ x\ xs\ (h\ xs)
\end{align*}

\item Notation: $\langle\![ b, f ]\!\rangle$
\end{itemize}

\end{frame}

\begin{frame}
We will provide some explanations about the algebra and coalgebra nature.

\end{frame}

\begin{frame}{Category}
$C = (obj, hom, \circ)$

Objects and morphisms between objects with their compositions.

Laws:
\begin{itemize}
\item Identity morphisms for each object
\item Composition is associative
\item Path equality
\end{itemize}

``Point'' is synonymous to ``Object''
\end{frame}

\begin{frame}{Categories: $Set$}
\begin{itemize}
\item $ob(Set)$ -- all sets
\item $hom(E,F)$ -- functions between sets $E$ and $F$
\item $\circ$ -- composition
\end{itemize}

\end{frame}

\begin{frame}{Categories: $Set$}
\begin{itemize}
\item $ob(Set)$ -- all sets
\item $hom(E,F)$ -- functions between sets $E$ and $F$
\item $\circ$ -- composition
\item Note: $ob(Set)$ is not a set itself (is a class).
\end{itemize}

\end{frame}

\begin{frame}{Categories}
\begin{itemize}
\item $Mon$: (monoids, morphisms, composition)
\item $Grp$: (groups, morphisms, composition)
\item $Hask$: (haskell types, functions, \hasqel{(.)})
\item ...
\end{itemize}

\end{frame}

\begin{frame}{Functor}
\begin{itemize}
\item Functor is a morphism between categories (preserves structures)
\end{itemize}

\end{frame}
\begin{frame}{Functor in FP}
\begin{itemize}
\item an (endo-)functor is an operation from types to types (from Hask to Hask)
\item preserves identity and composition.
\item functions can be 'mapped over' functors
\item Basic ones: identity, product, sum (tagged), arrow \dots

\end{itemize}

\end{frame}

\begin{frame}[fragile]{A usual recursive datatype}
\hin{9}{11}

is same as:
\hin{16}{20}
\end{frame}

\begin{frame}[fragile]{Test}
\hin{23}{24}
\end{frame}

\begin{frame}[fragile]{It is a functor!}

\hin{29}{32}

It is possible to construct an algebra on top of any functor.

\hin{55}{55}

We expect to be able to 'evaluate' children of \hasqel{Expr}.
Example:

\hin{37}{40}

\end{frame}

\begin{frame}[fragile]{What is an algebra?}

$(C, F, A, m)$
\begin{itemize}
\item Category $C$ ($Hask$, points are types of Haskell)
\item Endofunctor $F$ (maps Hask points into other Hask points)
\item Point $A$ (\textbf{carrier}) of category $C$ (some type).
\item Function $m$ mapping $F\ A \rightarrow A$
\end{itemize}

Hence our definition:

\hin{55}{55}

$C$ is implied ($Hask$), $F$ and $A$ are type-level, the rest is $m$, the function itself (of type \hasqel{Algebra f a}).

\textit{Look at the whiteboard for a fancy image!}

\end{frame}

\begin{frame}[fragile]{Initial algebra}
\begin{itemize}
\item There are infinitely many algebras based on same functor

\item One is particular \textbf{Initial algebra},

\item Does not 'forget' anything, preserves all information about input.

\item $\exists$ a homomorphism from initial algebra to any other algebra.

\item Assume: carrier is \hasqel{Fix f}, algebra is \hasqel{Fx} (its ctor).

\hin{55}{55}
\hin{63}{65}

\end{itemize}

\end{frame}

\begin{frame}[fragile]

Functor $f$ is fixed. Let $a$ be the carrier object for a new algebra.

~

\begin{tabular}{r | c | c}
 ~ & Carrier & Evaluator\\\hline
Initial algebra&   Fix f & Fx\\\hline
Some algebra &     a & alg \\
\end{tabular}

\end{frame}

\begin{frame}[fragile]{Constructing any algebra-1}

We want to get a homomorphism from initial algebra to some other algebra. Carrier mapper:

\hasqel{g:: Fix f -> a}

Remember: \hin{16}{16}

Thanks to the fact that $f$ is a functor, fmap is at our disposal to map :

\hasqel{fmap g :: f (Fix f) ->  f a}

\begin{center}
$
\begin{CD}
f (\text{Fix} \ f) @>\text{fmap} \ g>> f\ a\\
@VVFxV @VValgV\\
\text{Fix} \ f @>g>> a
\end{CD}
$

\end{center}
\end{frame}

\begin{frame}[fragile]{Constructing any algebra-2}

\hasqel{Fx} is lossless, thus invertible.

\hin{106}{107}

$
\begin{CD}
f (\text{Fix} \ f) @>\text{fmap} \ g>> f\ a\\
@VVFxV @VValgV\\
\text{Fix} \ f @>g>> a
\end{CD}
$
~~~~~becomes
$
\begin{CD}
f (\text{Fix} \ f) @>\text{fmap} \ g>> f\ a\\
@AAunFixA @VValgV\\
\text{Fix} \ f @>g>> a
\end{CD}
$

~

~

$g$ can be defined with unfix, fmap and evaluator:

\hin{110}{110}
\end{frame}

\begin{frame}[fragile]{Meet catamorphism}

\hin{110}{110}

\hin{115}{116}

Quick check:

\hin{43}{46}

\begin{verbatim}
*Main> :t cata alg
cata alg :: Fix ExprF -> String
\end{verbatim}
\end{frame}

\begin{frame}[fragile]{Coalgebra}

Algebra: $f\ a \rightarrow a$

Coalgebra: $a \rightarrow f\ a$

~

$
\begin{CD}
f (\text{Fix} \ f) @>\text{fmap} \ g>> f\ a\\
@VVFxV @VValgV\\
\text{Fix} \ f @>g>> a
\end{CD}
$
~~~~~becomes
$
\begin{CD}
f (\text{Fix} \ f) @<\text{fmap} \ g<< f\ a\\
@AAunFixA @AAcoalgA\\
\text{Fix} \ f @<g<< a
\end{CD}
$

~

~

~
The same reasoning about initial coalgebra applies.

\end{frame}

\begin{frame}{Coalgebra-2}
$\mu$ combines Fx and unFix.

\hin{141}{141}

\hin{142}{142}
\hin{55}{55}
\hin{145}{149}
\end{frame}

\begin{frame}{Coalgebra-3}

As $out$ is an initial algebra, $in$ is a terminal coalgebra (there exists a unique homomorphism from any coalgebra to $in$).
\begin{center}

$
\begin{CD}
f (\mu \ f) @<\text{fmap} \ g<< f\ a\\
@VVinV @AAcoalgA\\
\mu \ f @<g<< a
\end{CD}
$

~

~

~
\end{center}

\textit{Look at the whiteboard for a combined image}.

\end{frame}

\begin{frame}{Using fixed point}
We can define catamorphism and anamorphism in a non-recursive way.

\hin{168}{175}

\end{frame}

\begin{frame}{A note on notation}

Authors use this rather unusual notation:

$(f \xleftarrow{F} g) h = f \circ h_F \circ g$

$h_F$ is lifted inside the functor $F$.

Thus: $(f \xleftarrow{F} g)  = \lambda h. f \circ h_F \circ g$

Also:

$(f\ \Delta\  g) (x,y) = (f\  x, g \ y)$
\end{frame}

\begin{frame}{Notation summary}

\begin{itemize}
\item Catamorphism:

$(\!|\phi|\!)_F = \mu(\phi \xleftarrow{F} out)$

\hin{171}{171}

\item Anamorphism:

$[\!(\psi)\!]_F = \mu(in \xleftarrow{F} \psi )$

\hin{174}{174}

\item Hylomorphism:

$[\![\phi, \psi]\!]_F = \mu(\phi \xleftarrow{F} \psi )$

\item Paramorphism:

$\langle\![ \mathcal{E} ]\!\rangle = \mu ( \lambda f. \mathcal{E} \circ (id\ \Delta\ f)_F \circ out) $
\end{itemize}

\textit{Remember:} $(f \xleftarrow{F} g)  = \lambda h. f \circ h_F \circ g$

\end{frame}

\begin{frame}
For each morphism type we give:
\begin{itemize}
\item Evaluation rule
\item Uniqueness property
\item Fusion law (class-preserving functions mapping over morphism)
\end{itemize}
\end{frame}

\begin{frame}{Utility: fixed point fusion}

$f ( \bot ) = \bot \land f \circ g = h \circ f \Rightarrow f (\mu \ g) = \mu \ h $ (without proof)

\end{frame}

\begin{frame}[fragile]{Catamorphism}
\begin{itemize}
\item Evaluation rule:

$$(\!| \phi |\!)\circ in = \phi \circ (\!| \phi |\!)$$

Apply recursively, then $\phi$ again. Compare with fixed point:

$$x = \mu f \Rightarrow x = f \ x$$

\item \textbf{Uniqueness Property} (prove functions equality without explicit induction)

$f = (\!| \phi |\!)_F \equiv  f \circ \bot = ( \!| \phi |\!)_F \circ \bot \land f \circ in = \phi \circ f_{\mu\ F}$

Remember, \hasqel{In} is also a type ctor, applying isomorphism between $a$ and $F a$
\end{itemize}

\end{frame}

\begin{frame}{Catamorphisms - Fusion law}

Blend $cata\circ f$ into a single catamorphism.

$$f \circ (\!|\phi|\!) =  (\!|\psi|\!)  \Leftarrow f \ \bot = \bot \land f \circ \phi = \psi \circ f_{\mu F}$$

\textit{Look at the whiteboard for a fancy diagram}

~

\textbf{Useful variation}: $f$ is strict, not ``like $(\!|\psi|\!)$'':

$$f \circ (\!|\phi|\!) =  (\!|\psi|\!)  \Leftarrow f \circ \bot = (\!|\psi|\!)  \circ \bot \land f \circ \phi = \psi \circ f_{\mu F}$$

\end{frame}

\begin{frame}{Injective functions are catamorphisms}

$f: A \rightarrow B$\\
$\phi: A_F \rightarrow A$

Then:

$$f \circ (\!|\phi|\!) = (\!|f \circ \phi \circ g_F |\!) \Leftarrow \begin{cases} f \bot = \bot \\ g \circ f = id\end{cases}$$

Take $(\!|\phi|\!) = in$ :

$$f = (\!|f \circ in \circ g_F |\!) \Leftarrow \begin{cases} f \bot = \bot \\ g \circ f = id\end{cases}$$
\end{frame}

\begin{frame}{Catamorphisms preserve strictness}

A useful lemma for some proofs:

$$\mu F \circ \bot = \bot \Leftarrow \forall f : F f  \circ \bot = \bot$$

For cata:

$(\!|\phi |\!) _{F} \circ \bot = \bot \equiv \phi \circ \bot = \bot $

\end{frame}

\begin{frame}{Example: fold-unfold}
Whiteboard
\end{frame}

\begin{frame}{Anamorphisms}
Evaluation rule:

$$out \circ [\!(\psi )\!] = [\!(\psi )\!] _F \cdot \psi$$

Apply $[\!(\psi )\!] $, then apply $[\!(\psi )\!]_F$ to the result.

$$f = [\!(\psi )\!]  \equiv out \circ f = f_F \cdot \psi$$

\end{frame}

\begin{frame}{Fusion law}

$$[\!(\phi )\!] \circ f = [\!(\psi )\!]  \Leftarrow \phi \circ f = f_F \circ \psi$$

Proof by fixed point fusion theorem with $f := (\circ f)$, $g := in \leftarrow^F \phi $, $h :=in \leftarrow^L \psi$

\end{frame}
\begin{frame}{Surjective function is an anamorphism}

\end{frame}
\begin{frame}{Examples}

$iterate f = [\!(firstOfSum \circ id \Delta f  )\!] $

$takewhile\ p = [\!(secondOfSum\ 'map'\  (VOID  | id \circ ( not\ p \circ second)? ) \circ out \!] $

$f 'map' g \circ p?$ models if-then-else

\end{frame}
\begin{frame}

``Actually, even in Haskell recursion is not completely first class because the compiler does a terrible job of optimizing recursive code. This is why F-algebras and F-coalgebras are pervasive in high-performance Haskell libraries like vector, because they transform recursive code to non-recursive code, and the compiler does an amazing job of optimizing non-recursive code.'' (Gabriel Gonzales)

\end{frame}
\begin{frame}
Further reading:
\begin{itemize}
\item Control.Functor.Algebra
\end{itemize}
\end{frame}

\end{document}


text:
require 'spec_helper'

module Alchemy
  describe Admin::LayoutpagesController do
    before(:each) do
      authorize_user(:as_admin)
    end

    describe "#index" do
      it "should assign @layout_root" do
        alchemy_get :index
        expect(assigns(:layout_root)).to be_a(Page)
      end

      it "should assign @languages" do
        alchemy_get :index
        expect(assigns(:languages).first).to be_a(Language)
      end
    end
  end
end


text:
<?php

/*
	Class: RivetyCore_SessionSaveHandler

	About: Author
		Jaybill McCarthy

	About: License
		<http://rivety.com/docs/license>

	About: See Also
		Zend_Session_SaveHandler_Interface
*/
class RivetyCore_SessionSaveHandler implements Zend_Session_SaveHandler_Interface {

	/* Group: Instance Methods */

	/*
		Function: close
			TBD
	*/
	public function close() {
		//don't need to do anything, just has to be defined for the interface.
	}

	/*
		Function: destroy
			TBD

		Arguments:
			id - TBD

		Returns:
			void
	*/
	public function destroy($id) {
		$sessions_table = new Sessions();
		$where = $sessions_table->getAdapter()->quoteInto('id = ?', $id);
		RivetyCore_Log::info("Session handler: deleted session id " .$id);
		$sessions_table->delete($where);
	}

	/*
		Function: gc
			TBD

		Arguments:
			lifetime - TBD

		Returns:
			void
	*/
	public function gc($lifetime) {
		$sessions_table = new Sessions();
		$where = "expiration < " . time() - (int)RivetyCore_Registry::get('session_timeout');
		RivetyCore_Log::info("Session handler: deleted sessions: " .$where);
		//$sessions_table->delete($where);
	}

	/*
		Function: open
			TBD

		Arguments:
			save_path - TBD
			name - TBD

		Returns:
			void
	*/
	public function open($save_path, $name) {
		//don't need to do anything, just has to be defined for the interface.
	}

	/*
		Function: read
			TBD

		Arguments:
			id - TBD

		Returns:
			Either a row from the sessions table or false.
	*/
	public function read($id) {
		$sessions_table = new Sessions();
		$where = $sessions_table->getAdapter()->quoteInto('id = ?', $id);
		$session = $sessions_table->fetchRow($where);
		if (count($session) > 0) {
			$value = $session->value;
		} else {
			$value = false;
		}
		return $value;
	}

	/*
		Function: write

		Arguments:
			id - TBD
			value - TBD

		Returns:
			void
	*/
	public function write($id, $value) {
		$sessions_table = new Sessions();
		$lifetime = (int)RivetyCore_Registry::get('session_timeout');
		$expiration = time() + $lifetime;

		$data = array(
			'id' => $id,
			'value' => $value,
			'expiration' => $expiration,
		);

		$where = $sessions_table->getAdapter()->quoteInto('id = ?', $id);
		if($sessions_table->getCountByWhereClause($where) > 0){

			$sessions_table->update($data, $where);
			RivetyCore_Log::info("Session handler: updated session " .$id);
		} else {
			$id = $sessions_table->insert($data);
			RivetyCore_Log::info("Session handler: updating session " .$id);
		}
	}
}


text:
@class DBSHARINGInviteeInfo;

NS_ASSUME_NONNULL_BEGIN

#pragma mark - API Object

///
/// The `InviteeInfo` union.
///
/// Information about the recipient of a shared content invitation.
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBSHARINGInviteeInfo : NSObject <DBSerializable, NSCopying>

#pragma mark - Instance fields

/// The `DBSHARINGInviteeInfoTag` enum type represents the possible tag states
/// with which the `DBSHARINGInviteeInfo` union can exist.
typedef NS_ENUM(NSInteger, DBSHARINGInviteeInfoTag) {
  /// E-mail address of invited user.
  DBSHARINGInviteeInfoEmail,

  /// (no description).
  DBSHARINGInviteeInfoOther,

};

/// Represents the union's current tag state.
@property (nonatomic, readonly) DBSHARINGInviteeInfoTag tag;

/// E-mail address of invited user. @note Ensure the `isEmail` method returns
/// true before accessing, otherwise a runtime exception will be raised.
@property (nonatomic, readonly, copy) NSString *email;

#pragma mark - Constructors

///
/// Initializes union class with tag state of "email".
///
/// Description of the "email" tag state: E-mail address of invited user.
///
/// @param email E-mail address of invited user.
///
/// @return An initialized instance.
///
- (instancetype)initWithEmail:(NSString *)email;

///
/// Initializes union class with tag state of "other".
///
/// @return An initialized instance.
///
- (instancetype)initWithOther;

- (instancetype)init NS_UNAVAILABLE;

#pragma mark - Tag state methods

///
/// Retrieves whether the union's current tag state has value "email".
///
/// @note Call this method and ensure it returns true before accessing the
/// `email` property, otherwise a runtime exception will be thrown.
///
/// @return Whether the union's current tag state has value "email".
///
- (BOOL)isEmail;

///
/// Retrieves whether the union's current tag state has value "other".
///
/// @return Whether the union's current tag state has value "other".
///
- (BOOL)isOther;

///
/// Retrieves string value of union's current tag state.
///
/// @return A human-readable string representing the union's current tag state.
///
- (NSString *)tagName;

@end

#pragma mark - Serializer Object

///
/// The serialization class for the `DBSHARINGInviteeInfo` union.
///
@interface DBSHARINGInviteeInfoSerializer : NSObject

///
/// Serializes `DBSHARINGInviteeInfo` instances.
///
/// @param instance An instance of the `DBSHARINGInviteeInfo` API object.
///
/// @return A json-compatible dictionary representation of the
/// `DBSHARINGInviteeInfo` API object.
///
+ (nullable NSDictionary *)serialize:(DBSHARINGInviteeInfo *)instance;

///
/// Deserializes `DBSHARINGInviteeInfo` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBSHARINGInviteeInfo` API object.
///
/// @return An instantiation of the `DBSHARINGInviteeInfo` object.
///
+ (DBSHARINGInviteeInfo *)deserialize:(NSDictionary *)dict;

@end

NS_ASSUME_NONNULL_END


text:
<?xml version="1.0" encoding="utf-8"?>
<com.vipheyue.fastlib.fresh.header.GoogleCircleHookRefreshHeaderView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/refresh_header_height_google"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@android:color/transparent"
    android:orientation="vertical">

    <com.vipheyue.fastlib.fresh.header.GoogleCircleProgressView
        android:id="@+id/googleProgress"
        app:gcp_show_arrow="true"
        app:gcp_progress_stoke_width="2dp"
        app:gcp_arrow_height="6dp"
        app:gcp_arrow_width="8dp"
        android:layout_width="@dimen/refresh_drawable_size_google"
        android:layout_height="@dimen/refresh_drawable_size_google"
        android:layout_gravity="center" />
</com.vipheyue.fastlib.fresh.header.GoogleCircleHookRefreshHeaderView>


text:
#ifndef __CPU_O3_IEW_IMPL_IMPL_HH__
#define __CPU_O3_IEW_IMPL_IMPL_HH__

// @todo: Fix the instantaneous communication among all the stages within
// iew.  There's a clear delay between issue and execute, yet backwards
// communication happens simultaneously.

#include <queue>

#include "arch/utility.hh"
#include "config/the_isa.hh"
#include "cpu/checker/cpu.hh"
#include "cpu/o3/fu_pool.hh"
#include "cpu/o3/iew.hh"
#include "cpu/timebuf.hh"
#include "debug/Activity.hh"
#include "debug/Drain.hh"
#include "debug/IEW.hh"
#include "debug/O3PipeView.hh"
#include "params/DerivO3CPU.hh"

using namespace std;

template<class Impl>
DefaultIEW<Impl>::DefaultIEW(O3CPU *_cpu, DerivO3CPUParams *params)
    : issueToExecQueue(params->backComSize, params->forwardComSize),
      cpu(_cpu),
      instQueue(_cpu, this, params),
      ldstQueue(_cpu, this, params),
      fuPool(params->fuPool),
      commitToIEWDelay(params->commitToIEWDelay),
      renameToIEWDelay(params->renameToIEWDelay),
      issueToExecuteDelay(params->issueToExecuteDelay),
      dispatchWidth(params->dispatchWidth),
      issueWidth(params->issueWidth),
      wbOutstanding(0),
      wbWidth(params->wbWidth),
      numThreads(params->numThreads)
{
    if (dispatchWidth > Impl::MaxWidth)
        fatal("dispatchWidth (%d) is larger than compiled limit (%d),\n"
             "\tincrease MaxWidth in src/cpu/o3/impl.hh\n",
             dispatchWidth, static_cast<int>(Impl::MaxWidth));
    if (issueWidth > Impl::MaxWidth)
        fatal("issueWidth (%d) is larger than compiled limit (%d),\n"
             "\tincrease MaxWidth in src/cpu/o3/impl.hh\n",
             issueWidth, static_cast<int>(Impl::MaxWidth));
    if (wbWidth > Impl::MaxWidth)
        fatal("wbWidth (%d) is larger than compiled limit (%d),\n"
             "\tincrease MaxWidth in src/cpu/o3/impl.hh\n",
             wbWidth, static_cast<int>(Impl::MaxWidth));

    _status = Active;
    exeStatus = Running;
    wbStatus = Idle;

    // Setup wire to read instructions coming from issue.
    fromIssue = issueToExecQueue.getWire(-issueToExecuteDelay);

    // Instruction queue needs the queue between issue and execute.
    instQueue.setIssueToExecuteQueue(&issueToExecQueue);

    for (ThreadID tid = 0; tid < numThreads; tid++) {
        dispatchStatus[tid] = Running;
        stalls[tid].commit = false;
        fetchRedirect[tid] = false;
    }

    wbMax = wbWidth * params->wbDepth;

    updateLSQNextCycle = false;

    ableToIssue = true;

    skidBufferMax = (3 * (renameToIEWDelay * params->renameWidth)) + issueWidth;
}

template <class Impl>
std::string
DefaultIEW<Impl>::name() const
{
    return cpu->name() + ".iew";
}

template <class Impl>
void
DefaultIEW<Impl>::regProbePoints()
{
    ppDispatch = new ProbePointArg<DynInstPtr>(cpu->getProbeManager(), "Dispatch");
    ppMispredict = new ProbePointArg<DynInstPtr>(cpu->getProbeManager(), "Mispredict");
}

template <class Impl>
void
DefaultIEW<Impl>::regStats()
{
    using namespace Stats;

    instQueue.regStats();
    ldstQueue.regStats();

    iewIdleCycles
        .name(name() + ".iewIdleCycles")
        .desc("Number of cycles IEW is idle");

    iewSquashCycles
        .name(name() + ".iewSquashCycles")
        .desc("Number of cycles IEW is squashing");

    iewBlockCycles
        .name(name() + ".iewBlockCycles")
        .desc("Number of cycles IEW is blocking");

    iewUnblockCycles
        .name(name() + ".iewUnblockCycles")
        .desc("Number of cycles IEW is unblocking");

    iewDispatchedInsts
        .name(name() + ".iewDispatchedInsts")
        .desc("Number of instructions dispatched to IQ");

    iewDispSquashedInsts
        .name(name() + ".iewDispSquashedInsts")
        .desc("Number of squashed instructions skipped by dispatch");

    iewDispLoadInsts
        .name(name() + ".iewDispLoadInsts")
        .desc("Number of dispatched load instructions");

    iewDispStoreInsts
        .name(name() + ".iewDispStoreInsts")
        .desc("Number of dispatched store instructions");

    iewDispNonSpecInsts
        .name(name() + ".iewDispNonSpecInsts")
        .desc("Number of dispatched non-speculative instructions");

    iewIQFullEvents
        .name(name() + ".iewIQFullEvents")
        .desc("Number of times the IQ has become full, causing a stall");

    iewLSQFullEvents
        .name(name() + ".iewLSQFullEvents")
        .desc("Number of times the LSQ has become full, causing a stall");

    memOrderViolationEvents
        .name(name() + ".memOrderViolationEvents")
        .desc("Number of memory order violations");

    predictedTakenIncorrect
        .name(name() + ".predictedTakenIncorrect")
        .desc("Number of branches that were predicted taken incorrectly");

    predictedNotTakenIncorrect
        .name(name() + ".predictedNotTakenIncorrect")
        .desc("Number of branches that were predicted not taken incorrectly");

    branchMispredicts
        .name(name() + ".branchMispredicts")
        .desc("Number of branch mispredicts detected at execute");

    branchMispredicts = predictedTakenIncorrect + predictedNotTakenIncorrect;

    iewExecutedInsts
        .name(name() + ".iewExecutedInsts")
        .desc("Number of executed instructions");

    iewExecLoadInsts
        .init(cpu->numThreads)
        .name(name() + ".iewExecLoadInsts")
        .desc("Number of load instructions executed")
        .flags(total);

    iewExecSquashedInsts
        .name(name() + ".iewExecSquashedInsts")
        .desc("Number of squashed instructions skipped in execute");

    iewExecutedSwp
        .init(cpu->numThreads)
        .name(name() + ".exec_swp")
        .desc("number of swp insts executed")
        .flags(total);

    iewExecutedNop
        .init(cpu->numThreads)
        .name(name() + ".exec_nop")
        .desc("number of nop insts executed")
        .flags(total);

    iewExecutedRefs
        .init(cpu->numThreads)
        .name(name() + ".exec_refs")
        .desc("number of memory reference insts executed")
        .flags(total);

    iewExecutedBranches
        .init(cpu->numThreads)
        .name(name() + ".exec_branches")
        .desc("Number of branches executed")
        .flags(total);

    iewExecStoreInsts
        .name(name() + ".exec_stores")
        .desc("Number of stores executed")
        .flags(total);
    iewExecStoreInsts = iewExecutedRefs - iewExecLoadInsts;

    iewExecRate
        .name(name() + ".exec_rate")
        .desc("Inst execution rate")
        .flags(total);

    iewExecRate = iewExecutedInsts / cpu->numCycles;

    iewInstsToCommit
        .init(cpu->numThreads)
        .name(name() + ".wb_sent")
        .desc("cumulative count of insts sent to commit")
        .flags(total);

    writebackCount
        .init(cpu->numThreads)
        .name(name() + ".wb_count")
        .desc("cumulative count of insts written-back")
        .flags(total);

    producerInst
        .init(cpu->numThreads)
        .name(name() + ".wb_producers")
        .desc("num instructions producing a value")
        .flags(total);

    consumerInst
        .init(cpu->numThreads)
        .name(name() + ".wb_consumers")
        .desc("num instructions consuming a value")
        .flags(total);

    wbPenalized
        .init(cpu->numThreads)
        .name(name() + ".wb_penalized")
        .desc("number of instrctions required to write to 'other' IQ")
        .flags(total);

    wbPenalizedRate
        .name(name() + ".wb_penalized_rate")
        .desc ("fraction of instructions written-back that wrote to 'other' IQ")
        .flags(total);

    wbPenalizedRate = wbPenalized / writebackCount;

    wbFanout
        .name(name() + ".wb_fanout")
        .desc("average fanout of values written-back")
        .flags(total);

    wbFanout = producerInst / consumerInst;

    wbRate
        .name(name() + ".wb_rate")
        .desc("insts written-back per cycle")
        .flags(total);
    wbRate = writebackCount / cpu->numCycles;
}

template<class Impl>
void
DefaultIEW<Impl>::startupStage()
{
    for (ThreadID tid = 0; tid < numThreads; tid++) {
        toRename->iewInfo[tid].usedIQ = true;
        toRename->iewInfo[tid].freeIQEntries =
            instQueue.numFreeEntries(tid);

        toRename->iewInfo[tid].usedLSQ = true;
        toRename->iewInfo[tid].freeLSQEntries =
            ldstQueue.numFreeEntries(tid);
    }

    // Initialize the checker's dcache port here
    if (cpu->checker) {
        cpu->checker->setDcachePort(&cpu->getDataPort());
    }

    cpu->activateStage(O3CPU::IEWIdx);
}

template<class Impl>
void
DefaultIEW<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr)
{
    timeBuffer = tb_ptr;

    // Setup wire to read information from time buffer, from commit.
    fromCommit = timeBuffer->getWire(-commitToIEWDelay);

    // Setup wire to write information back to previous stages.
    toRename = timeBuffer->getWire(0);

    toFetch = timeBuffer->getWire(0);

    // Instruction queue also needs main time buffer.
    instQueue.setTimeBuffer(tb_ptr);
}

template<class Impl>
void
DefaultIEW<Impl>::setRenameQueue(TimeBuffer<RenameStruct> *rq_ptr)
{
    renameQueue = rq_ptr;

    // Setup wire to read information from rename queue.
    fromRename = renameQueue->getWire(-renameToIEWDelay);
}

template<class Impl>
void
DefaultIEW<Impl>::setIEWQueue(TimeBuffer<IEWStruct> *iq_ptr)
{
    iewQueue = iq_ptr;

    // Setup wire to write instructions to commit.
    toCommit = iewQueue->getWire(0);
}

template<class Impl>
void
DefaultIEW<Impl>::setActiveThreads(list<ThreadID> *at_ptr)
{
    activeThreads = at_ptr;

    ldstQueue.setActiveThreads(at_ptr);
    instQueue.setActiveThreads(at_ptr);
}

template<class Impl>
void
DefaultIEW<Impl>::setScoreboard(Scoreboard *sb_ptr)
{
    scoreboard = sb_ptr;
}

template <class Impl>
bool
DefaultIEW<Impl>::isDrained() const
{
    bool drained(ldstQueue.isDrained());

    for (ThreadID tid = 0; tid < numThreads; tid++) {
        if (!insts[tid].empty()) {
            DPRINTF(Drain, "%i: Insts not empty.\n", tid);
            drained = false;
        }
        if (!skidBuffer[tid].empty()) {
            DPRINTF(Drain, "%i: Skid buffer not empty.\n", tid);
            drained = false;
        }
    }

    // Also check the FU pool as instructions are "stored" in FU
    // completion events until they are done and not accounted for
    // above
    if (drained && !fuPool->isDrained()) {
        DPRINTF(Drain, "FU pool still busy.\n");
        drained = false;
    }

    return drained;
}

template <class Impl>
void
DefaultIEW<Impl>::drainSanityCheck() const
{
    assert(isDrained());

    instQueue.drainSanityCheck();
    ldstQueue.drainSanityCheck();
}

template <class Impl>
void
DefaultIEW<Impl>::takeOverFrom()
{
    // Reset all state.
    _status = Active;
    exeStatus = Running;
    wbStatus = Idle;

    instQueue.takeOverFrom();
    ldstQueue.takeOverFrom();
    fuPool->takeOverFrom();

    startupStage();
    cpu->activityThisCycle();

    for (ThreadID tid = 0; tid < numThreads; tid++) {
        dispatchStatus[tid] = Running;
        stalls[tid].commit = false;
        fetchRedirect[tid] = false;
    }

    updateLSQNextCycle = false;

    for (int i = 0; i < issueToExecQueue.getSize(); ++i) {
        issueToExecQueue.advance();
    }
}

template<class Impl>
void
DefaultIEW<Impl>::squash(ThreadID tid)
{
    DPRINTF(IEW, "[tid:%i]: Squashing all instructions.\n", tid);

    // Tell the IQ to start squashing.
    instQueue.squash(tid);

    // Tell the LDSTQ to start squashing.
    ldstQueue.squash(fromCommit->commitInfo[tid].doneSeqNum, tid);
    updatedQueues = true;

    // Clear the skid buffer in case it has any data in it.
    DPRINTF(IEW, "[tid:%i]: Removing skidbuffer instructions until [sn:%i].\n",
            tid, fromCommit->commitInfo[tid].doneSeqNum);

    while (!skidBuffer[tid].empty()) {
        if (skidBuffer[tid].front()->isLoad() ||
            skidBuffer[tid].front()->isStore() ) {
            toRename->iewInfo[tid].dispatchedToLSQ++;
        }

        toRename->iewInfo[tid].dispatched++;

        skidBuffer[tid].pop();
    }

    emptyRenameInsts(tid);
}

template<class Impl>
void
DefaultIEW<Impl>::squashDueToBranch(DynInstPtr &inst, ThreadID tid)
{
    DPRINTF(IEW, "[tid:%i]: Squashing from a specific instruction, PC: %s "
            "[sn:%i].\n", tid, inst->pcState(), inst->seqNum);

    if (!toCommit->squash[tid] ||
            inst->seqNum < toCommit->squashedSeqNum[tid]) {
        toCommit->squash[tid] = true;
        toCommit->squashedSeqNum[tid] = inst->seqNum;
        toCommit->branchTaken[tid] = inst->pcState().branching();

        TheISA::PCState pc = inst->pcState();
        TheISA::advancePC(pc, inst->staticInst);

        toCommit->pc[tid] = pc;
        toCommit->mispredictInst[tid] = inst;
        toCommit->includeSquashInst[tid] = false;

        wroteToTimeBuffer = true;
    }

}

template<class Impl>
void
DefaultIEW<Impl>::squashDueToMemOrder(DynInstPtr &inst, ThreadID tid)
{
    DPRINTF(IEW, "[tid:%i]: Memory violation, squashing violator and younger "
            "insts, PC: %s [sn:%i].\n", tid, inst->pcState(), inst->seqNum);
    // Need to include inst->seqNum in the following comparison to cover the
    // corner case when a branch misprediction and a memory violation for the
    // same instruction (e.g. load PC) are detected in the same cycle.  In this
    // case the memory violator should take precedence over the branch
    // misprediction because it requires the violator itself to be included in
    // the squash.
    if (!toCommit->squash[tid] ||
            inst->seqNum <= toCommit->squashedSeqNum[tid]) {
        toCommit->squash[tid] = true;

        toCommit->squashedSeqNum[tid] = inst->seqNum;
        toCommit->pc[tid] = inst->pcState();
        toCommit->mispredictInst[tid] = NULL;

        // Must include the memory violator in the squash.
        toCommit->includeSquashInst[tid] = true;

        wroteToTimeBuffer = true;
    }
}

template<class Impl>
void
DefaultIEW<Impl>::squashDueToMemBlocked(DynInstPtr &inst, ThreadID tid)
{
    DPRINTF(IEW, "[tid:%i]: Memory blocked, squashing load and younger insts, "
            "PC: %s [sn:%i].\n", tid, inst->pcState(), inst->seqNum);
    if (!toCommit->squash[tid] ||
            inst->seqNum < toCommit->squashedSeqNum[tid]) {
        toCommit->squash[tid] = true;

        toCommit->squashedSeqNum[tid] = inst->seqNum;
        toCommit->pc[tid] = inst->pcState();
        toCommit->mispredictInst[tid] = NULL;

        // Must include the broadcasted SN in the squash.
        toCommit->includeSquashInst[tid] = true;

        ldstQueue.setLoadBlockedHandled(tid);

        wroteToTimeBuffer = true;
    }
}

template<class Impl>
void
DefaultIEW<Impl>::block(ThreadID tid)
{
    DPRINTF(IEW, "[tid:%u]: Blocking.\n", tid);

    if (dispatchStatus[tid] != Blocked &&
        dispatchStatus[tid] != Unblocking) {
        toRename->iewBlock[tid] = true;
        wroteToTimeBuffer = true;
    }

    // Add the current inputs to the skid buffer so they can be
    // reprocessed when this stage unblocks.
    skidInsert(tid);

    dispatchStatus[tid] = Blocked;
}

template<class Impl>
void
DefaultIEW<Impl>::unblock(ThreadID tid)
{
    DPRINTF(IEW, "[tid:%i]: Reading instructions out of the skid "
            "buffer %u.\n",tid, tid);

    // If the skid bufffer is empty, signal back to previous stages to unblock.
    // Also switch status to running.
    if (skidBuffer[tid].empty()) {
        toRename->iewUnblock[tid] = true;
        wroteToTimeBuffer = true;
        DPRINTF(IEW, "[tid:%i]: Done unblocking.\n",tid);
        dispatchStatus[tid] = Running;
    }
}

template<class Impl>
void
DefaultIEW<Impl>::wakeDependents(DynInstPtr &inst)
{
    instQueue.wakeDependents(inst);
}

template<class Impl>
void
DefaultIEW<Impl>::rescheduleMemInst(DynInstPtr &inst)
{
    instQueue.rescheduleMemInst(inst);
}

template<class Impl>
void
DefaultIEW<Impl>::replayMemInst(DynInstPtr &inst)
{
    instQueue.replayMemInst(inst);
}

template<class Impl>
void
DefaultIEW<Impl>::instToCommit(DynInstPtr &inst)
{
    // This function should not be called after writebackInsts in a
    // single cycle.  That will cause problems with an instruction
    // being added to the queue to commit without being processed by
    // writebackInsts prior to being sent to commit.

    // First check the time slot that this instruction will write
    // to.  If there are free write ports at the time, then go ahead
    // and write the instruction to that time.  If there are not,
    // keep looking back to see where's the first time there's a
    // free slot.
    while ((*iewQueue)[wbCycle].insts[wbNumInst]) {
        ++wbNumInst;
        if (wbNumInst == wbWidth) {
            ++wbCycle;
            wbNumInst = 0;
        }

        assert((wbCycle * wbWidth + wbNumInst) <= wbMax);
    }

    DPRINTF(IEW, "Current wb cycle: %i, width: %i, numInst: %i\nwbActual:%i\n",
            wbCycle, wbWidth, wbNumInst, wbCycle * wbWidth + wbNumInst);
    // Add finished instruction to queue to commit.
    (*iewQueue)[wbCycle].insts[wbNumInst] = inst;
    (*iewQueue)[wbCycle].size++;
}

template <class Impl>
unsigned
DefaultIEW<Impl>::validInstsFromRename()
{
    unsigned inst_count = 0;

    for (int i=0; i<fromRename->size; i++) {
        if (!fromRename->insts[i]->isSquashed())
            inst_count++;
    }

    return inst_count;
}

template<class Impl>
void
DefaultIEW<Impl>::skidInsert(ThreadID tid)
{
    DynInstPtr inst = NULL;

    while (!insts[tid].empty()) {
        inst = insts[tid].front();

        insts[tid].pop();

        DPRINTF(IEW,"[tid:%i]: Inserting [sn:%lli] PC:%s into "
                "dispatch skidBuffer %i\n",tid, inst->seqNum,
                inst->pcState(),tid);

        skidBuffer[tid].push(inst);
    }

    assert(skidBuffer[tid].size() <= skidBufferMax &&
           "Skidbuffer Exceeded Max Size");
}

template<class Impl>
int
DefaultIEW<Impl>::skidCount()
{
    int max=0;

    list<ThreadID>::iterator threads = activeThreads->begin();
    list<ThreadID>::iterator end = activeThreads->end();

    while (threads != end) {
        ThreadID tid = *threads++;
        unsigned thread_count = skidBuffer[tid].size();
        if (max < thread_count)
            max = thread_count;
    }

    return max;
}

template<class Impl>
bool
DefaultIEW<Impl>::skidsEmpty()
{
    list<ThreadID>::iterator threads = activeThreads->begin();
    list<ThreadID>::iterator end = activeThreads->end();

    while (threads != end) {
        ThreadID tid = *threads++;

        if (!skidBuffer[tid].empty())
            return false;
    }

    return true;
}

template <class Impl>
void
DefaultIEW<Impl>::updateStatus()
{
    bool any_unblocking = false;

    list<ThreadID>::iterator threads = activeThreads->begin();
    list<ThreadID>::iterator end = activeThreads->end();

    while (threads != end) {
        ThreadID tid = *threads++;

        if (dispatchStatus[tid] == Unblocking) {
            any_unblocking = true;
            break;
        }
    }

    // If there are no ready instructions waiting to be scheduled by the IQ,
    // and there's no stores waiting to write back, and dispatch is not
    // unblocking, then there is no internal activity for the IEW stage.
    instQueue.intInstQueueReads++;
    if (_status == Active && !instQueue.hasReadyInsts() &&
        !ldstQueue.willWB() && !any_unblocking) {
        DPRINTF(IEW, "IEW switching to idle\n");

        deactivateStage();

        _status = Inactive;
    } else if (_status == Inactive && (instQueue.hasReadyInsts() ||
                                       ldstQueue.willWB() ||
                                       any_unblocking)) {
        // Otherwise there is internal activity.  Set to active.
        DPRINTF(IEW, "IEW switching to active\n");

        activateStage();

        _status = Active;
    }
}

template <class Impl>
void
DefaultIEW<Impl>::resetEntries()
{
    instQueue.resetEntries();
    ldstQueue.resetEntries();
}

template <class Impl>
void
DefaultIEW<Impl>::readStallSignals(ThreadID tid)
{
    if (fromCommit->commitBlock[tid]) {
        stalls[tid].commit = true;
    }

    if (fromCommit->commitUnblock[tid]) {
        assert(stalls[tid].commit);
        stalls[tid].commit = false;
    }
}

template <class Impl>
bool
DefaultIEW<Impl>::checkStall(ThreadID tid)
{
    bool ret_val(false);

    if (stalls[tid].commit) {
        DPRINTF(IEW,"[tid:%i]: Stall from Commit stage detected.\n",tid);
        ret_val = true;
    } else if (instQueue.isFull(tid)) {
        DPRINTF(IEW,"[tid:%i]: Stall: IQ  is full.\n",tid);
        ret_val = true;
    } else if (ldstQueue.isFull(tid)) {
        DPRINTF(IEW,"[tid:%i]: Stall: LSQ is full\n",tid);

        if (ldstQueue.numLoads(tid) > 0 ) {

            DPRINTF(IEW,"[tid:%i]: LSQ oldest load: [sn:%i] \n",
                    tid,ldstQueue.getLoadHeadSeqNum(tid));
        }

        if (ldstQueue.numStores(tid) > 0) {

            DPRINTF(IEW,"[tid:%i]: LSQ oldest store: [sn:%i] \n",
                    tid,ldstQueue.getStoreHeadSeqNum(tid));
        }

        ret_val = true;
    } else if (ldstQueue.isStalled(tid)) {
        DPRINTF(IEW,"[tid:%i]: Stall: LSQ stall detected.\n",tid);
        ret_val = true;
    }

    return ret_val;
}

template <class Impl>
void
DefaultIEW<Impl>::checkSignalsAndUpdate(ThreadID tid)
{
    // Check if there's a squash signal, squash if there is
    // Check stall signals, block if there is.
    // If status was Blocked
    //     if so then go to unblocking
    // If status was Squashing
    //     check if squashing is not high.  Switch to running this cycle.

    readStallSignals(tid);

    if (fromCommit->commitInfo[tid].squash) {
        squash(tid);

        if (dispatchStatus[tid] == Blocked ||
            dispatchStatus[tid] == Unblocking) {
            toRename->iewUnblock[tid] = true;
            wroteToTimeBuffer = true;
        }

        dispatchStatus[tid] = Squashing;
        fetchRedirect[tid] = false;
        return;
    }

    if (fromCommit->commitInfo[tid].robSquashing) {
        DPRINTF(IEW, "[tid:%i]: ROB is still squashing.\n", tid);

        dispatchStatus[tid] = Squashing;
        emptyRenameInsts(tid);
        wroteToTimeBuffer = true;
        return;
    }

    if (checkStall(tid)) {
        block(tid);
        dispatchStatus[tid] = Blocked;
        return;
    }

    if (dispatchStatus[tid] == Blocked) {
        // Status from previous cycle was blocked, but there are no more stall
        // conditions.  Switch over to unblocking.
        DPRINTF(IEW, "[tid:%i]: Done blocking, switching to unblocking.\n",
                tid);

        dispatchStatus[tid] = Unblocking;

        unblock(tid);

        return;
    }

    if (dispatchStatus[tid] == Squashing) {
        // Switch status to running if rename isn't being told to block or
        // squash this cycle.
        DPRINTF(IEW, "[tid:%i]: Done squashing, switching to running.\n",
                tid);

        dispatchStatus[tid] = Running;

        return;
    }
}

template <class Impl>
void
DefaultIEW<Impl>::sortInsts()
{
    int insts_from_rename = fromRename->size;
#ifdef DEBUG
    for (ThreadID tid = 0; tid < numThreads; tid++)
        assert(insts[tid].empty());
#endif
    for (int i = 0; i < insts_from_rename; ++i) {
        insts[fromRename->insts[i]->threadNumber].push(fromRename->insts[i]);
    }
}

template <class Impl>
void
DefaultIEW<Impl>::emptyRenameInsts(ThreadID tid)
{
    DPRINTF(IEW, "[tid:%i]: Removing incoming rename instructions\n", tid);

    while (!insts[tid].empty()) {

        if (insts[tid].front()->isLoad() ||
            insts[tid].front()->isStore() ) {
            toRename->iewInfo[tid].dispatchedToLSQ++;
        }

        toRename->iewInfo[tid].dispatched++;

        insts[tid].pop();
    }
}

template <class Impl>
void
DefaultIEW<Impl>::wakeCPU()
{
    cpu->wakeCPU();
}

template <class Impl>
void
DefaultIEW<Impl>::activityThisCycle()
{
    DPRINTF(Activity, "Activity this cycle.\n");
    cpu->activityThisCycle();
}

template <class Impl>
inline void
DefaultIEW<Impl>::activateStage()
{
    DPRINTF(Activity, "Activating stage.\n");
    cpu->activateStage(O3CPU::IEWIdx);
}

template <class Impl>
inline void
DefaultIEW<Impl>::deactivateStage()
{
    DPRINTF(Activity, "Deactivating stage.\n");
    cpu->deactivateStage(O3CPU::IEWIdx);
}

template<class Impl>
void
DefaultIEW<Impl>::dispatch(ThreadID tid)
{
    // If status is Running or idle,
    //     call dispatchInsts()
    // If status is Unblocking,
    //     buffer any instructions coming from rename
    //     continue trying to empty skid buffer
    //     check if stall conditions have passed

    if (dispatchStatus[tid] == Blocked) {
        ++iewBlockCycles;

    } else if (dispatchStatus[tid] == Squashing) {
        ++iewSquashCycles;
    }

    // Dispatch should try to dispatch as many instructions as its bandwidth
    // will allow, as long as it is not currently blocked.
    if (dispatchStatus[tid] == Running ||
        dispatchStatus[tid] == Idle) {
        DPRINTF(IEW, "[tid:%i] Not blocked, so attempting to run "
                "dispatch.\n", tid);

        dispatchInsts(tid);
    } else if (dispatchStatus[tid] == Unblocking) {
        // Make sure that the skid buffer has something in it if the
        // status is unblocking.
        assert(!skidsEmpty());

        // If the status was unblocking, then instructions from the skid
        // buffer were used.  Remove those instructions and handle
        // the rest of unblocking.
        dispatchInsts(tid);

        ++iewUnblockCycles;

        if (validInstsFromRename()) {
            // Add the current inputs to the skid buffer so they can be
            // reprocessed when this stage unblocks.
            skidInsert(tid);
        }

        unblock(tid);
    }
}

template <class Impl>
void
DefaultIEW<Impl>::dispatchInsts(ThreadID tid)
{
    // Obtain instructions from skid buffer if unblocking, or queue from rename
    // otherwise.
    std::queue<DynInstPtr> &insts_to_dispatch =
        dispatchStatus[tid] == Unblocking ?
        skidBuffer[tid] : insts[tid];

    int insts_to_add = insts_to_dispatch.size();

    DynInstPtr inst;
    bool add_to_iq = false;
    int dis_num_inst = 0;

    // Loop through the instructions, putting them in the instruction
    // queue.
    for ( ; dis_num_inst < insts_to_add &&
              dis_num_inst < dispatchWidth;
          ++dis_num_inst)
    {
        inst = insts_to_dispatch.front();

        if (dispatchStatus[tid] == Unblocking) {
            DPRINTF(IEW, "[tid:%i]: Issue: Examining instruction from skid "
                    "buffer\n", tid);
        }

        // Make sure there's a valid instruction there.
        assert(inst);

        DPRINTF(IEW, "[tid:%i]: Issue: Adding PC %s [sn:%lli] [tid:%i] to "
                "IQ.\n",
                tid, inst->pcState(), inst->seqNum, inst->threadNumber);

        // Be sure to mark these instructions as ready so that the
        // commit stage can go ahead and execute them, and mark
        // them as issued so the IQ doesn't reprocess them.

        // Check for squashed instructions.
        if (inst->isSquashed()) {
            DPRINTF(IEW, "[tid:%i]: Issue: Squashed instruction encountered, "
                    "not adding to IQ.\n", tid);

            ++iewDispSquashedInsts;

            insts_to_dispatch.pop();

            //Tell Rename That An Instruction has been processed
            if (inst->isLoad() || inst->isStore()) {
                toRename->iewInfo[tid].dispatchedToLSQ++;
            }
            toRename->iewInfo[tid].dispatched++;

            continue;
        }

        // Check for full conditions.
        if (instQueue.isFull(tid)) {
            DPRINTF(IEW, "[tid:%i]: Issue: IQ has become full.\n", tid);

            // Call function to start blocking.
            block(tid);

            // Set unblock to false. Special case where we are using
            // skidbuffer (unblocking) instructions but then we still
            // get full in the IQ.
            toRename->iewUnblock[tid] = false;

            ++iewIQFullEvents;
            break;
        } else if (ldstQueue.isFull(tid)) {
            DPRINTF(IEW, "[tid:%i]: Issue: LSQ has become full.\n",tid);

            // Call function to start blocking.
            block(tid);

            // Set unblock to false. Special case where we are using
            // skidbuffer (unblocking) instructions but then we still
            // get full in the IQ.
            toRename->iewUnblock[tid] = false;

            ++iewLSQFullEvents;
            break;
        }

        // Otherwise issue the instruction just fine.
        if (inst->isLoad()) {
            DPRINTF(IEW, "[tid:%i]: Issue: Memory instruction "
                    "encountered, adding to LSQ.\n", tid);

            // Reserve a spot in the load store queue for this
            // memory access.
            ldstQueue.insertLoad(inst);

            ++iewDispLoadInsts;

            add_to_iq = true;

            toRename->iewInfo[tid].dispatchedToLSQ++;
        } else if (inst->isStore()) {
            DPRINTF(IEW, "[tid:%i]: Issue: Memory instruction "
                    "encountered, adding to LSQ.\n", tid);

            ldstQueue.insertStore(inst);

            ++iewDispStoreInsts;

            if (inst->isStoreConditional()) {
                // Store conditionals need to be set as "canCommit()"
                // so that commit can process them when they reach the
                // head of commit.
                // @todo: This is somewhat specific to Alpha.
                inst->setCanCommit();
                instQueue.insertNonSpec(inst);
                add_to_iq = false;

                ++iewDispNonSpecInsts;
            } else {
                add_to_iq = true;
            }

            toRename->iewInfo[tid].dispatchedToLSQ++;
        } else if (inst->isMemBarrier() || inst->isWriteBarrier()) {
            // Same as non-speculative stores.
            inst->setCanCommit();
            instQueue.insertBarrier(inst);
            add_to_iq = false;
        } else if (inst->isNop()) {
            DPRINTF(IEW, "[tid:%i]: Issue: Nop instruction encountered, "
                    "skipping.\n", tid);

            inst->setIssued();
            inst->setExecuted();
            inst->setCanCommit();

            instQueue.recordProducer(inst);

            iewExecutedNop[tid]++;

            add_to_iq = false;
        } else if (inst->isExecuted()) {
            assert(0 && "Instruction shouldn't be executed.\n");
            DPRINTF(IEW, "Issue: Executed branch encountered, "
                    "skipping.\n");

            inst->setIssued();
            inst->setCanCommit();

            instQueue.recordProducer(inst);

            add_to_iq = false;
        } else {
            add_to_iq = true;
        }
        if (inst->isNonSpeculative()) {
            DPRINTF(IEW, "[tid:%i]: Issue: Nonspeculative instruction "
                    "encountered, skipping.\n", tid);

            // Same as non-speculative stores.
            inst->setCanCommit();

            // Specifically insert it as nonspeculative.
            instQueue.insertNonSpec(inst);

            ++iewDispNonSpecInsts;

            add_to_iq = false;
        }

        // If the instruction queue is not full, then add the
        // instruction.
        if (add_to_iq) {
            instQueue.insert(inst);
        }

        insts_to_dispatch.pop();

        toRename->iewInfo[tid].dispatched++;

        ++iewDispatchedInsts;

#if TRACING_ON
        inst->dispatchTick = curTick() - inst->fetchTick;
#endif
        ppDispatch->notify(inst);
    }

    if (!insts_to_dispatch.empty()) {
        DPRINTF(IEW,"[tid:%i]: Issue: Bandwidth Full. Blocking.\n", tid);
        block(tid);
        toRename->iewUnblock[tid] = false;
    }

    if (dispatchStatus[tid] == Idle && dis_num_inst) {
        dispatchStatus[tid] = Running;

        updatedQueues = true;
    }

    dis_num_inst = 0;
}

template <class Impl>
void
DefaultIEW<Impl>::printAvailableInsts()
{
    int inst = 0;

    std::cout << "Available Instructions: ";

    while (fromIssue->insts[inst]) {

        if (inst%3==0) std::cout << "\n\t";

        std::cout << "PC: " << fromIssue->insts[inst]->pcState()
             << " TN: " << fromIssue->insts[inst]->threadNumber
             << " SN: " << fromIssue->insts[inst]->seqNum << " | ";

        inst++;

    }

    std::cout << "\n";
}

template <class Impl>
void
DefaultIEW<Impl>::executeInsts()
{
    wbNumInst = 0;
    wbCycle = 0;

    list<ThreadID>::iterator threads = activeThreads->begin();
    list<ThreadID>::iterator end = activeThreads->end();

    while (threads != end) {
        ThreadID tid = *threads++;
        fetchRedirect[tid] = false;
    }

    // Uncomment this if you want to see all available instructions.
    // @todo This doesn't actually work anymore, we should fix it.
//    printAvailableInsts();

    // Execute/writeback any instructions that are available.
    int insts_to_execute = fromIssue->size;
    int inst_num = 0;
    for (; inst_num < insts_to_execute;
          ++inst_num) {

        DPRINTF(IEW, "Execute: Executing instructions from IQ.\n");

        DynInstPtr inst = instQueue.getInstToExecute();

        DPRINTF(IEW, "Execute: Processing PC %s, [tid:%i] [sn:%i].\n",
                inst->pcState(), inst->threadNumber,inst->seqNum);

        // Check if the instruction is squashed; if so then skip it
        if (inst->isSquashed()) {
            DPRINTF(IEW, "Execute: Instruction was squashed. PC: %s, [tid:%i]"
                         " [sn:%i]\n", inst->pcState(), inst->threadNumber,
                         inst->seqNum);

            // Consider this instruction executed so that commit can go
            // ahead and retire the instruction.
            inst->setExecuted();

            // Not sure if I should set this here or just let commit try to
            // commit any squashed instructions.  I like the latter a bit more.
            inst->setCanCommit();

            ++iewExecSquashedInsts;

            decrWb(inst->seqNum);
            continue;
        }

        Fault fault = NoFault;

        // Execute instruction.
        // Note that if the instruction faults, it will be handled
        // at the commit stage.
        if (inst->isMemRef()) {
            DPRINTF(IEW, "Execute: Calculating address for memory "
                    "reference.\n");

            // Tell the LDSTQ to execute this instruction (if it is a load).
            if (inst->isLoad()) {
                // Loads will mark themselves as executed, and their writeback
                // event adds the instruction to the queue to commit
                fault = ldstQueue.executeLoad(inst);

                if (inst->isTranslationDelayed() &&
                    fault == NoFault) {
                    // A hw page table walk is currently going on; the
                    // instruction must be deferred.
                    DPRINTF(IEW, "Execute: Delayed translation, deferring "
                            "load.\n");
                    instQueue.deferMemInst(inst);
                    continue;
                }

                if (inst->isDataPrefetch() || inst->isInstPrefetch()) {
                    inst->fault = NoFault;
                }
            } else if (inst->isStore()) {
                fault = ldstQueue.executeStore(inst);

                if (inst->isTranslationDelayed() &&
                    fault == NoFault) {
                    // A hw page table walk is currently going on; the
                    // instruction must be deferred.
                    DPRINTF(IEW, "Execute: Delayed translation, deferring "
                            "store.\n");
                    instQueue.deferMemInst(inst);
                    continue;
                }

                // If the store had a fault then it may not have a mem req
                if (fault != NoFault || !inst->readPredicate() ||
                        !inst->isStoreConditional()) {
                    // If the instruction faulted, then we need to send it along
                    // to commit without the instruction completing.
                    // Send this instruction to commit, also make sure iew stage
                    // realizes there is activity.
                    inst->setExecuted();
                    instToCommit(inst);
                    activityThisCycle();
                }

                // Store conditionals will mark themselves as
                // executed, and their writeback event will add the
                // instruction to the queue to commit.
            } else {
                panic("Unexpected memory type!\n");
            }

        } else {
            // If the instruction has already faulted, then skip executing it.
            // Such case can happen when it faulted during ITLB translation.
            // If we execute the instruction (even if it's a nop) the fault
            // will be replaced and we will lose it.
            if (inst->getFault() == NoFault) {
                inst->execute();
                if (!inst->readPredicate())
                    inst->forwardOldRegs();
            }

            inst->setExecuted();

            instToCommit(inst);
        }

        updateExeInstStats(inst);

        // Check if branch prediction was correct, if not then we need
        // to tell commit to squash in flight instructions.  Only
        // handle this if there hasn't already been something that
        // redirects fetch in this group of instructions.

        // This probably needs to prioritize the redirects if a different
        // scheduler is used.  Currently the scheduler schedules the oldest
        // instruction first, so the branch resolution order will be correct.
        ThreadID tid = inst->threadNumber;

        if (!fetchRedirect[tid] ||
            !toCommit->squash[tid] ||
            toCommit->squashedSeqNum[tid] > inst->seqNum) {

            // Prevent testing for misprediction on load instructions,
            // that have not been executed.
            bool loadNotExecuted = !inst->isExecuted() && inst->isLoad();

            if (inst->mispredicted() && !loadNotExecuted) {
                fetchRedirect[tid] = true;

                DPRINTF(IEW, "Execute: Branch mispredict detected.\n");
                DPRINTF(IEW, "Predicted target was PC: %s.\n",
                        inst->readPredTarg());
                DPRINTF(IEW, "Execute: Redirecting fetch to PC: %s.\n",
                        inst->pcState());
                // If incorrect, then signal the ROB that it must be squashed.
                squashDueToBranch(inst, tid);

                ppMispredict->notify(inst);

                if (inst->readPredTaken()) {
                    predictedTakenIncorrect++;
                } else {
                    predictedNotTakenIncorrect++;
                }
            } else if (ldstQueue.violation(tid)) {
                assert(inst->isMemRef());
                // If there was an ordering violation, then get the
                // DynInst that caused the violation.  Note that this
                // clears the violation signal.
                DynInstPtr violator;
                violator = ldstQueue.getMemDepViolator(tid);

                DPRINTF(IEW, "LDSTQ detected a violation. Violator PC: %s "
                        "[sn:%lli], inst PC: %s [sn:%lli]. Addr is: %#x.\n",
                        violator->pcState(), violator->seqNum,
                        inst->pcState(), inst->seqNum, inst->physEffAddr);

                fetchRedirect[tid] = true;

                // Tell the instruction queue that a violation has occured.
                instQueue.violation(inst, violator);

                // Squash.
                squashDueToMemOrder(violator, tid);

                ++memOrderViolationEvents;
            } else if (ldstQueue.loadBlocked(tid) &&
                       !ldstQueue.isLoadBlockedHandled(tid)) {
                fetchRedirect[tid] = true;

                DPRINTF(IEW, "Load operation couldn't execute because the "
                        "memory system is blocked.  PC: %s [sn:%lli]\n",
                        inst->pcState(), inst->seqNum);

                squashDueToMemBlocked(inst, tid);
            }
        } else {
            // Reset any state associated with redirects that will not
            // be used.
            if (ldstQueue.violation(tid)) {
                assert(inst->isMemRef());

                DynInstPtr violator = ldstQueue.getMemDepViolator(tid);

                DPRINTF(IEW, "LDSTQ detected a violation.  Violator PC: "
                        "%s, inst PC: %s.  Addr is: %#x.\n",
                        violator->pcState(), inst->pcState(),
                        inst->physEffAddr);
                DPRINTF(IEW, "Violation will not be handled because "
                        "already squashing\n");

                ++memOrderViolationEvents;
            }
            if (ldstQueue.loadBlocked(tid) &&
                !ldstQueue.isLoadBlockedHandled(tid)) {
                DPRINTF(IEW, "Load operation couldn't execute because the "
                        "memory system is blocked.  PC: %s [sn:%lli]\n",
                        inst->pcState(), inst->seqNum);
                DPRINTF(IEW, "Blocked load will not be handled because "
                        "already squashing\n");

                ldstQueue.setLoadBlockedHandled(tid);
            }

        }
    }

    // Update and record activity if we processed any instructions.
    if (inst_num) {
        if (exeStatus == Idle) {
            exeStatus = Running;
        }

        updatedQueues = true;

        cpu->activityThisCycle();
    }

    // Need to reset this in case a writeback event needs to write into the
    // iew queue.  That way the writeback event will write into the correct
    // spot in the queue.
    wbNumInst = 0;

}

template <class Impl>
void
DefaultIEW<Impl>::writebackInsts()
{
    // Loop through the head of the time buffer and wake any
    // dependents.  These instructions are about to write back.  Also
    // mark scoreboard that this instruction is finally complete.
    // Either have IEW have direct access to scoreboard, or have this
    // as part of backwards communication.
    for (int inst_num = 0; inst_num < wbWidth &&
             toCommit->insts[inst_num]; inst_num++) {
        DynInstPtr inst = toCommit->insts[inst_num];
        ThreadID tid = inst->threadNumber;

        DPRINTF(IEW, "Sending instructions to commit, [sn:%lli] PC %s.\n",
                inst->seqNum, inst->pcState());

        iewInstsToCommit[tid]++;

        // Some instructions will be sent to commit without having
        // executed because they need commit to handle them.
        // E.g. Uncached loads have not actually executed when they
        // are first sent to commit.  Instead commit must tell the LSQ
        // when it's ready to execute the uncached load.
        if (!inst->isSquashed() && inst->isExecuted() && inst->getFault() == NoFault) {
            int dependents = instQueue.wakeDependents(inst);

            for (int i = 0; i < inst->numDestRegs(); i++) {
                //mark as Ready
                DPRINTF(IEW,"Setting Destination Register %i\n",
                        inst->renamedDestRegIdx(i));
                scoreboard->setReg(inst->renamedDestRegIdx(i));
            }

            if (dependents) {
                producerInst[tid]++;
                consumerInst[tid]+= dependents;
            }
            writebackCount[tid]++;
        }

        decrWb(inst->seqNum);
    }
}

template<class Impl>
void
DefaultIEW<Impl>::tick()
{
    wbNumInst = 0;
    wbCycle = 0;

    wroteToTimeBuffer = false;
    updatedQueues = false;

    sortInsts();

    // Free function units marked as being freed this cycle.
    fuPool->processFreeUnits();

    list<ThreadID>::iterator threads = activeThreads->begin();
    list<ThreadID>::iterator end = activeThreads->end();

    // Check stall and squash signals, dispatch any instructions.
    while (threads != end) {
        ThreadID tid = *threads++;

        DPRINTF(IEW,"Issue: Processing [tid:%i]\n",tid);

        checkSignalsAndUpdate(tid);
        dispatch(tid);
    }

    if (exeStatus != Squashing) {
        executeInsts();

        writebackInsts();

        // Have the instruction queue try to schedule any ready instructions.
        // (In actuality, this scheduling is for instructions that will
        // be executed next cycle.)
        instQueue.scheduleReadyInsts();

        // Also should advance its own time buffers if the stage ran.
        // Not the best place for it, but this works (hopefully).
        issueToExecQueue.advance();
    }

    bool broadcast_free_entries = false;

    if (updatedQueues || exeStatus == Running || updateLSQNextCycle) {
        exeStatus = Idle;
        updateLSQNextCycle = false;

        broadcast_free_entries = true;
    }

    // Writeback any stores using any leftover bandwidth.
    ldstQueue.writebackStores();

    // Check the committed load/store signals to see if there's a load
    // or store to commit.  Also check if it's being told to execute a
    // nonspeculative instruction.
    // This is pretty inefficient...

    threads = activeThreads->begin();
    while (threads != end) {
        ThreadID tid = (*threads++);

        DPRINTF(IEW,"Processing [tid:%i]\n",tid);

        // Update structures based on instructions committed.
        if (fromCommit->commitInfo[tid].doneSeqNum != 0 &&
            !fromCommit->commitInfo[tid].squash &&
            !fromCommit->commitInfo[tid].robSquashing) {

            ldstQueue.commitStores(fromCommit->commitInfo[tid].doneSeqNum,tid);

            ldstQueue.commitLoads(fromCommit->commitInfo[tid].doneSeqNum,tid);

            updateLSQNextCycle = true;
            instQueue.commit(fromCommit->commitInfo[tid].doneSeqNum,tid);
        }

        if (fromCommit->commitInfo[tid].nonSpecSeqNum != 0) {

            //DPRINTF(IEW,"NonspecInst from thread %i",tid);
            if (fromCommit->commitInfo[tid].uncached) {
                instQueue.replayMemInst(fromCommit->commitInfo[tid].uncachedLoad);
                fromCommit->commitInfo[tid].uncachedLoad->setAtCommit();
            } else {
                instQueue.scheduleNonSpec(
                    fromCommit->commitInfo[tid].nonSpecSeqNum);
            }
        }

        if (broadcast_free_entries) {
            toFetch->iewInfo[tid].iqCount =
                instQueue.getCount(tid);
            toFetch->iewInfo[tid].ldstqCount =
                ldstQueue.getCount(tid);

            toRename->iewInfo[tid].usedIQ = true;
            toRename->iewInfo[tid].freeIQEntries =
                instQueue.numFreeEntries(tid);
            toRename->iewInfo[tid].usedLSQ = true;
            toRename->iewInfo[tid].freeLSQEntries =
                ldstQueue.numFreeEntries(tid);

            wroteToTimeBuffer = true;
        }

        DPRINTF(IEW, "[tid:%i], Dispatch dispatched %i instructions.\n",
                tid, toRename->iewInfo[tid].dispatched);
    }

    DPRINTF(IEW, "IQ has %i free entries (Can schedule: %i).  "
            "LSQ has %i free entries.\n",
            instQueue.numFreeEntries(), instQueue.hasReadyInsts(),
            ldstQueue.numFreeEntries());

    updateStatus();

    if (wroteToTimeBuffer) {
        DPRINTF(Activity, "Activity this cycle.\n");
        cpu->activityThisCycle();
    }
}

template <class Impl>
void
DefaultIEW<Impl>::updateExeInstStats(DynInstPtr &inst)
{
    ThreadID tid = inst->threadNumber;

    iewExecutedInsts++;

#if TRACING_ON
    if (DTRACE(O3PipeView)) {
        inst->completeTick = curTick() - inst->fetchTick;
    }
#endif

    //
    //  Control operations
    //
    if (inst->isControl())
        iewExecutedBranches[tid]++;

    //
    //  Memory operations
    //
    if (inst->isMemRef()) {
        iewExecutedRefs[tid]++;

        if (inst->isLoad()) {
            iewExecLoadInsts[tid]++;
        }
    }
}

template <class Impl>
void
DefaultIEW<Impl>::checkMisprediction(DynInstPtr &inst)
{
    ThreadID tid = inst->threadNumber;

    if (!fetchRedirect[tid] ||
        !toCommit->squash[tid] ||
        toCommit->squashedSeqNum[tid] > inst->seqNum) {

        if (inst->mispredicted()) {
            fetchRedirect[tid] = true;

            DPRINTF(IEW, "Execute: Branch mispredict detected.\n");
            DPRINTF(IEW, "Predicted target was PC:%#x, NPC:%#x.\n",
                    inst->predInstAddr(), inst->predNextInstAddr());
            DPRINTF(IEW, "Execute: Redirecting fetch to PC: %#x,"
                    " NPC: %#x.\n", inst->nextInstAddr(),
                    inst->nextInstAddr());
            // If incorrect, then signal the ROB that it must be squashed.
            squashDueToBranch(inst, tid);

            if (inst->readPredTaken()) {
                predictedTakenIncorrect++;
            } else {
                predictedNotTakenIncorrect++;
            }
        }
    }
}

#endif//__CPU_O3_IEW_IMPL_IMPL_HH__


text:
package com.commonsware.tapoffnow;

import android.app.assist.AssistContent;
import android.app.assist.AssistStructure;
import android.content.Context;
import android.os.Bundle;
import android.service.voice.VoiceInteractionSession;
import android.widget.Toast;

public class AssistLoggerSession extends
  VoiceInteractionSession {

  public AssistLoggerSession(Context context) {
    super(context);
  }

  @Override
  public void onHandleAssist(Bundle data,
                             AssistStructure structure,
                             AssistContent content) {
    super.onHandleAssist(data, structure, content);

    Toast
      .makeText(getContext(), R.string.msg_blocked,
        Toast.LENGTH_LONG)
      .show();
  }
}


text:
module AzVariablesHelper
end