commit_impl.hh revision 13641
1/*
2 * Copyright 2014 Google, Inc.
3 * Copyright (c) 2010-2014, 2017 ARM Limited
4 * All rights reserved
5 *
6 * The license below extends only to copyright in the software and shall
7 * not be construed as granting a license to any other intellectual
8 * property including but not limited to intellectual property relating
9 * to a hardware implementation of the functionality of the software
10 * licensed hereunder.  You may use the software subject to the license
11 * terms below provided that you ensure that this notice is replicated
12 * unmodified and in its entirety in all distributions of the software,
13 * modified or unmodified, in source code or in binary form.
14 *
15 * Copyright (c) 2004-2006 The Regents of The University of Michigan
16 * All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
20 * met: redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer;
22 * redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution;
25 * neither the name of the copyright holders nor the names of its
26 * contributors may be used to endorse or promote products derived from
27 * this software without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 *
41 * Authors: Kevin Lim
42 *          Korey Sewell
43 */
44#ifndef __CPU_O3_COMMIT_IMPL_HH__
45#define __CPU_O3_COMMIT_IMPL_HH__
46
47#include <algorithm>
48#include <set>
49#include <string>
50
51#include "arch/utility.hh"
52#include "base/cp_annotate.hh"
53#include "base/loader/symtab.hh"
54#include "base/logging.hh"
55#include "config/the_isa.hh"
56#include "cpu/checker/cpu.hh"
57#include "cpu/o3/commit.hh"
58#include "cpu/o3/thread_state.hh"
59#include "cpu/base.hh"
60#include "cpu/exetrace.hh"
61#include "cpu/timebuf.hh"
62#include "debug/Activity.hh"
63#include "debug/Commit.hh"
64#include "debug/CommitRate.hh"
65#include "debug/Drain.hh"
66#include "debug/ExecFaulting.hh"
67#include "debug/O3PipeView.hh"
68#include "params/DerivO3CPU.hh"
69#include "sim/faults.hh"
70#include "sim/full_system.hh"
71
72using namespace std;
73
74template <class Impl>
75void
76DefaultCommit<Impl>::processTrapEvent(ThreadID tid)
77{
78    // This will get reset by commit if it was switched out at the
79    // time of this event processing.
80    trapSquash[tid] = true;
81}
82
83template <class Impl>
84DefaultCommit<Impl>::DefaultCommit(O3CPU *_cpu, DerivO3CPUParams *params)
85    : commitPolicy(params->smtCommitPolicy),
86      cpu(_cpu),
87      iewToCommitDelay(params->iewToCommitDelay),
88      commitToIEWDelay(params->commitToIEWDelay),
89      renameToROBDelay(params->renameToROBDelay),
90      fetchToCommitDelay(params->commitToFetchDelay),
91      renameWidth(params->renameWidth),
92      commitWidth(params->commitWidth),
93      numThreads(params->numThreads),
94      drainPending(false),
95      drainImminent(false),
96      trapLatency(params->trapLatency),
97      canHandleInterrupts(true),
98      avoidQuiesceLiveLock(false)
99{
100    if (commitWidth > Impl::MaxWidth)
101        fatal("commitWidth (%d) is larger than compiled limit (%d),\n"
102             "\tincrease MaxWidth in src/cpu/o3/impl.hh\n",
103             commitWidth, static_cast<int>(Impl::MaxWidth));
104
105    _status = Active;
106    _nextStatus = Inactive;
107
108    if (commitPolicy == CommitPolicy::RoundRobin) {
109        //Set-Up Priority List
110        for (ThreadID tid = 0; tid < numThreads; tid++) {
111            priority_list.push_back(tid);
112        }
113    }
114
115    for (ThreadID tid = 0; tid < Impl::MaxThreads; tid++) {
116        commitStatus[tid] = Idle;
117        changedROBNumEntries[tid] = false;
118        trapSquash[tid] = false;
119        tcSquash[tid] = false;
120        squashAfterInst[tid] = nullptr;
121        pc[tid].set(0);
122        youngestSeqNum[tid] = 0;
123        lastCommitedSeqNum[tid] = 0;
124        trapInFlight[tid] = false;
125        committedStores[tid] = false;
126        checkEmptyROB[tid] = false;
127        renameMap[tid] = nullptr;
128    }
129    interrupt = NoFault;
130}
131
132template <class Impl>
133std::string
134DefaultCommit<Impl>::name() const
135{
136    return cpu->name() + ".commit";
137}
138
139template <class Impl>
140void
141DefaultCommit<Impl>::regProbePoints()
142{
143    ppCommit = new ProbePointArg<DynInstPtr>(cpu->getProbeManager(), "Commit");
144    ppCommitStall = new ProbePointArg<DynInstPtr>(cpu->getProbeManager(), "CommitStall");
145    ppSquash = new ProbePointArg<DynInstPtr>(cpu->getProbeManager(), "Squash");
146}
147
148template <class Impl>
149void
150DefaultCommit<Impl>::regStats()
151{
152    using namespace Stats;
153    commitSquashedInsts
154        .name(name() + ".commitSquashedInsts")
155        .desc("The number of squashed insts skipped by commit")
156        .prereq(commitSquashedInsts);
157
158    commitNonSpecStalls
159        .name(name() + ".commitNonSpecStalls")
160        .desc("The number of times commit has been forced to stall to "
161              "communicate backwards")
162        .prereq(commitNonSpecStalls);
163
164    branchMispredicts
165        .name(name() + ".branchMispredicts")
166        .desc("The number of times a branch was mispredicted")
167        .prereq(branchMispredicts);
168
169    numCommittedDist
170        .init(0,commitWidth,1)
171        .name(name() + ".committed_per_cycle")
172        .desc("Number of insts commited each cycle")
173        .flags(Stats::pdf)
174        ;
175
176    instsCommitted
177        .init(cpu->numThreads)
178        .name(name() + ".committedInsts")
179        .desc("Number of instructions committed")
180        .flags(total)
181        ;
182
183    opsCommitted
184        .init(cpu->numThreads)
185        .name(name() + ".committedOps")
186        .desc("Number of ops (including micro ops) committed")
187        .flags(total)
188        ;
189
190    statComSwp
191        .init(cpu->numThreads)
192        .name(name() + ".swp_count")
193        .desc("Number of s/w prefetches committed")
194        .flags(total)
195        ;
196
197    statComRefs
198        .init(cpu->numThreads)
199        .name(name() +  ".refs")
200        .desc("Number of memory references committed")
201        .flags(total)
202        ;
203
204    statComLoads
205        .init(cpu->numThreads)
206        .name(name() +  ".loads")
207        .desc("Number of loads committed")
208        .flags(total)
209        ;
210
211    statComMembars
212        .init(cpu->numThreads)
213        .name(name() +  ".membars")
214        .desc("Number of memory barriers committed")
215        .flags(total)
216        ;
217
218    statComBranches
219        .init(cpu->numThreads)
220        .name(name() + ".branches")
221        .desc("Number of branches committed")
222        .flags(total)
223        ;
224
225    statComFloating
226        .init(cpu->numThreads)
227        .name(name() + ".fp_insts")
228        .desc("Number of committed floating point instructions.")
229        .flags(total)
230        ;
231
232    statComVector
233        .init(cpu->numThreads)
234        .name(name() + ".vec_insts")
235        .desc("Number of committed Vector instructions.")
236        .flags(total)
237        ;
238
239    statComInteger
240        .init(cpu->numThreads)
241        .name(name()+".int_insts")
242        .desc("Number of committed integer instructions.")
243        .flags(total)
244        ;
245
246    statComFunctionCalls
247        .init(cpu->numThreads)
248        .name(name()+".function_calls")
249        .desc("Number of function calls committed.")
250        .flags(total)
251        ;
252
253    statCommittedInstType
254        .init(numThreads,Enums::Num_OpClass)
255        .name(name() + ".op_class")
256        .desc("Class of committed instruction")
257        .flags(total | pdf | dist)
258        ;
259    statCommittedInstType.ysubnames(Enums::OpClassStrings);
260
261    commitEligibleSamples
262        .name(name() + ".bw_lim_events")
263        .desc("number cycles where commit BW limit reached")
264        ;
265}
266
267template <class Impl>
268void
269DefaultCommit<Impl>::setThreads(std::vector<Thread *> &threads)
270{
271    thread = threads;
272}
273
274template <class Impl>
275void
276DefaultCommit<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr)
277{
278    timeBuffer = tb_ptr;
279
280    // Setup wire to send information back to IEW.
281    toIEW = timeBuffer->getWire(0);
282
283    // Setup wire to read data from IEW (for the ROB).
284    robInfoFromIEW = timeBuffer->getWire(-iewToCommitDelay);
285}
286
287template <class Impl>
288void
289DefaultCommit<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
290{
291    fetchQueue = fq_ptr;
292
293    // Setup wire to get instructions from rename (for the ROB).
294    fromFetch = fetchQueue->getWire(-fetchToCommitDelay);
295}
296
297template <class Impl>
298void
299DefaultCommit<Impl>::setRenameQueue(TimeBuffer<RenameStruct> *rq_ptr)
300{
301    renameQueue = rq_ptr;
302
303    // Setup wire to get instructions from rename (for the ROB).
304    fromRename = renameQueue->getWire(-renameToROBDelay);
305}
306
307template <class Impl>
308void
309DefaultCommit<Impl>::setIEWQueue(TimeBuffer<IEWStruct> *iq_ptr)
310{
311    iewQueue = iq_ptr;
312
313    // Setup wire to get instructions from IEW.
314    fromIEW = iewQueue->getWire(-iewToCommitDelay);
315}
316
317template <class Impl>
318void
319DefaultCommit<Impl>::setIEWStage(IEW *iew_stage)
320{
321    iewStage = iew_stage;
322}
323
324template<class Impl>
325void
326DefaultCommit<Impl>::setActiveThreads(list<ThreadID> *at_ptr)
327{
328    activeThreads = at_ptr;
329}
330
331template <class Impl>
332void
333DefaultCommit<Impl>::setRenameMap(RenameMap rm_ptr[])
334{
335    for (ThreadID tid = 0; tid < numThreads; tid++)
336        renameMap[tid] = &rm_ptr[tid];
337}
338
339template <class Impl>
340void
341DefaultCommit<Impl>::setROB(ROB *rob_ptr)
342{
343    rob = rob_ptr;
344}
345
346template <class Impl>
347void
348DefaultCommit<Impl>::startupStage()
349{
350    rob->setActiveThreads(activeThreads);
351    rob->resetEntries();
352
353    // Broadcast the number of free entries.
354    for (ThreadID tid = 0; tid < numThreads; tid++) {
355        toIEW->commitInfo[tid].usedROB = true;
356        toIEW->commitInfo[tid].freeROBEntries = rob->numFreeEntries(tid);
357        toIEW->commitInfo[tid].emptyROB = true;
358    }
359
360    // Commit must broadcast the number of free entries it has at the
361    // start of the simulation, so it starts as active.
362    cpu->activateStage(O3CPU::CommitIdx);
363
364    cpu->activityThisCycle();
365}
366
367template <class Impl>
368void
369DefaultCommit<Impl>::clearStates(ThreadID tid)
370{
371    commitStatus[tid] = Idle;
372    changedROBNumEntries[tid] = false;
373    checkEmptyROB[tid] = false;
374    trapInFlight[tid] = false;
375    committedStores[tid] = false;
376    trapSquash[tid] = false;
377    tcSquash[tid] = false;
378    pc[tid].set(0);
379    lastCommitedSeqNum[tid] = 0;
380    squashAfterInst[tid] = NULL;
381}
382
383template <class Impl>
384void
385DefaultCommit<Impl>::drain()
386{
387    drainPending = true;
388}
389
390template <class Impl>
391void
392DefaultCommit<Impl>::drainResume()
393{
394    drainPending = false;
395    drainImminent = false;
396}
397
398template <class Impl>
399void
400DefaultCommit<Impl>::drainSanityCheck() const
401{
402    assert(isDrained());
403    rob->drainSanityCheck();
404}
405
406template <class Impl>
407bool
408DefaultCommit<Impl>::isDrained() const
409{
410    /* Make sure no one is executing microcode. There are two reasons
411     * for this:
412     * - Hardware virtualized CPUs can't switch into the middle of a
413     *   microcode sequence.
414     * - The current fetch implementation will most likely get very
415     *   confused if it tries to start fetching an instruction that
416     *   is executing in the middle of a ucode sequence that changes
417     *   address mappings. This can happen on for example x86.
418     */
419    for (ThreadID tid = 0; tid < numThreads; tid++) {
420        if (pc[tid].microPC() != 0)
421            return false;
422    }
423
424    /* Make sure that all instructions have finished committing before
425     * declaring the system as drained. We want the pipeline to be
426     * completely empty when we declare the CPU to be drained. This
427     * makes debugging easier since CPU handover and restoring from a
428     * checkpoint with a different CPU should have the same timing.
429     */
430    return rob->isEmpty() &&
431        interrupt == NoFault;
432}
433
434template <class Impl>
435void
436DefaultCommit<Impl>::takeOverFrom()
437{
438    _status = Active;
439    _nextStatus = Inactive;
440    for (ThreadID tid = 0; tid < numThreads; tid++) {
441        commitStatus[tid] = Idle;
442        changedROBNumEntries[tid] = false;
443        trapSquash[tid] = false;
444        tcSquash[tid] = false;
445        squashAfterInst[tid] = NULL;
446    }
447    rob->takeOverFrom();
448}
449
450template <class Impl>
451void
452DefaultCommit<Impl>::deactivateThread(ThreadID tid)
453{
454    list<ThreadID>::iterator thread_it = std::find(priority_list.begin(),
455            priority_list.end(), tid);
456
457    if (thread_it != priority_list.end()) {
458        priority_list.erase(thread_it);
459    }
460}
461
462
463template <class Impl>
464void
465DefaultCommit<Impl>::updateStatus()
466{
467    // reset ROB changed variable
468    list<ThreadID>::iterator threads = activeThreads->begin();
469    list<ThreadID>::iterator end = activeThreads->end();
470
471    while (threads != end) {
472        ThreadID tid = *threads++;
473
474        changedROBNumEntries[tid] = false;
475
476        // Also check if any of the threads has a trap pending
477        if (commitStatus[tid] == TrapPending ||
478            commitStatus[tid] == FetchTrapPending) {
479            _nextStatus = Active;
480        }
481    }
482
483    if (_nextStatus == Inactive && _status == Active) {
484        DPRINTF(Activity, "Deactivating stage.\n");
485        cpu->deactivateStage(O3CPU::CommitIdx);
486    } else if (_nextStatus == Active && _status == Inactive) {
487        DPRINTF(Activity, "Activating stage.\n");
488        cpu->activateStage(O3CPU::CommitIdx);
489    }
490
491    _status = _nextStatus;
492}
493
494template <class Impl>
495bool
496DefaultCommit<Impl>::changedROBEntries()
497{
498    list<ThreadID>::iterator threads = activeThreads->begin();
499    list<ThreadID>::iterator end = activeThreads->end();
500
501    while (threads != end) {
502        ThreadID tid = *threads++;
503
504        if (changedROBNumEntries[tid]) {
505            return true;
506        }
507    }
508
509    return false;
510}
511
512template <class Impl>
513size_t
514DefaultCommit<Impl>::numROBFreeEntries(ThreadID tid)
515{
516    return rob->numFreeEntries(tid);
517}
518
519template <class Impl>
520void
521DefaultCommit<Impl>::generateTrapEvent(ThreadID tid, Fault inst_fault)
522{
523    DPRINTF(Commit, "Generating trap event for [tid:%i]\n", tid);
524
525    EventFunctionWrapper *trap = new EventFunctionWrapper(
526        [this, tid]{ processTrapEvent(tid); },
527        "Trap", true, Event::CPU_Tick_Pri);
528
529    Cycles latency = dynamic_pointer_cast<SyscallRetryFault>(inst_fault) ?
530                     cpu->syscallRetryLatency : trapLatency;
531
532    cpu->schedule(trap, cpu->clockEdge(latency));
533    trapInFlight[tid] = true;
534    thread[tid]->trapPending = true;
535}
536
537template <class Impl>
538void
539DefaultCommit<Impl>::generateTCEvent(ThreadID tid)
540{
541    assert(!trapInFlight[tid]);
542    DPRINTF(Commit, "Generating TC squash event for [tid:%i]\n", tid);
543
544    tcSquash[tid] = true;
545}
546
547template <class Impl>
548void
549DefaultCommit<Impl>::squashAll(ThreadID tid)
550{
551    // If we want to include the squashing instruction in the squash,
552    // then use one older sequence number.
553    // Hopefully this doesn't mess things up.  Basically I want to squash
554    // all instructions of this thread.
555    InstSeqNum squashed_inst = rob->isEmpty(tid) ?
556        lastCommitedSeqNum[tid] : rob->readHeadInst(tid)->seqNum - 1;
557
558    // All younger instructions will be squashed. Set the sequence
559    // number as the youngest instruction in the ROB (0 in this case.
560    // Hopefully nothing breaks.)
561    youngestSeqNum[tid] = lastCommitedSeqNum[tid];
562
563    rob->squash(squashed_inst, tid);
564    changedROBNumEntries[tid] = true;
565
566    // Send back the sequence number of the squashed instruction.
567    toIEW->commitInfo[tid].doneSeqNum = squashed_inst;
568
569    // Send back the squash signal to tell stages that they should
570    // squash.
571    toIEW->commitInfo[tid].squash = true;
572
573    // Send back the rob squashing signal so other stages know that
574    // the ROB is in the process of squashing.
575    toIEW->commitInfo[tid].robSquashing = true;
576
577    toIEW->commitInfo[tid].mispredictInst = NULL;
578    toIEW->commitInfo[tid].squashInst = NULL;
579
580    toIEW->commitInfo[tid].pc = pc[tid];
581}
582
583template <class Impl>
584void
585DefaultCommit<Impl>::squashFromTrap(ThreadID tid)
586{
587    squashAll(tid);
588
589    DPRINTF(Commit, "Squashing from trap, restarting at PC %s\n", pc[tid]);
590
591    thread[tid]->trapPending = false;
592    thread[tid]->noSquashFromTC = false;
593    trapInFlight[tid] = false;
594
595    trapSquash[tid] = false;
596
597    commitStatus[tid] = ROBSquashing;
598    cpu->activityThisCycle();
599}
600
601template <class Impl>
602void
603DefaultCommit<Impl>::squashFromTC(ThreadID tid)
604{
605    squashAll(tid);
606
607    DPRINTF(Commit, "Squashing from TC, restarting at PC %s\n", pc[tid]);
608
609    thread[tid]->noSquashFromTC = false;
610    assert(!thread[tid]->trapPending);
611
612    commitStatus[tid] = ROBSquashing;
613    cpu->activityThisCycle();
614
615    tcSquash[tid] = false;
616}
617
618template <class Impl>
619void
620DefaultCommit<Impl>::squashFromSquashAfter(ThreadID tid)
621{
622    DPRINTF(Commit, "Squashing after squash after request, "
623            "restarting at PC %s\n", pc[tid]);
624
625    squashAll(tid);
626    // Make sure to inform the fetch stage of which instruction caused
627    // the squash. It'll try to re-fetch an instruction executing in
628    // microcode unless this is set.
629    toIEW->commitInfo[tid].squashInst = squashAfterInst[tid];
630    squashAfterInst[tid] = NULL;
631
632    commitStatus[tid] = ROBSquashing;
633    cpu->activityThisCycle();
634}
635
636template <class Impl>
637void
638DefaultCommit<Impl>::squashAfter(ThreadID tid, const DynInstPtr &head_inst)
639{
640    DPRINTF(Commit, "Executing squash after for [tid:%i] inst [sn:%lli]\n",
641            tid, head_inst->seqNum);
642
643    assert(!squashAfterInst[tid] || squashAfterInst[tid] == head_inst);
644    commitStatus[tid] = SquashAfterPending;
645    squashAfterInst[tid] = head_inst;
646}
647
648template <class Impl>
649void
650DefaultCommit<Impl>::tick()
651{
652    wroteToTimeBuffer = false;
653    _nextStatus = Inactive;
654
655    if (activeThreads->empty())
656        return;
657
658    list<ThreadID>::iterator threads = activeThreads->begin();
659    list<ThreadID>::iterator end = activeThreads->end();
660
661    // Check if any of the threads are done squashing.  Change the
662    // status if they are done.
663    while (threads != end) {
664        ThreadID tid = *threads++;
665
666        // Clear the bit saying if the thread has committed stores
667        // this cycle.
668        committedStores[tid] = false;
669
670        if (commitStatus[tid] == ROBSquashing) {
671
672            if (rob->isDoneSquashing(tid)) {
673                commitStatus[tid] = Running;
674            } else {
675                DPRINTF(Commit,"[tid:%u]: Still Squashing, cannot commit any"
676                        " insts this cycle.\n", tid);
677                rob->doSquash(tid);
678                toIEW->commitInfo[tid].robSquashing = true;
679                wroteToTimeBuffer = true;
680            }
681        }
682    }
683
684    commit();
685
686    markCompletedInsts();
687
688    threads = activeThreads->begin();
689
690    while (threads != end) {
691        ThreadID tid = *threads++;
692
693        if (!rob->isEmpty(tid) && rob->readHeadInst(tid)->readyToCommit()) {
694            // The ROB has more instructions it can commit. Its next status
695            // will be active.
696            _nextStatus = Active;
697
698            const DynInstPtr &inst M5_VAR_USED = rob->readHeadInst(tid);
699
700            DPRINTF(Commit,"[tid:%i]: Instruction [sn:%lli] PC %s is head of"
701                    " ROB and ready to commit\n",
702                    tid, inst->seqNum, inst->pcState());
703
704        } else if (!rob->isEmpty(tid)) {
705            const DynInstPtr &inst = rob->readHeadInst(tid);
706
707            ppCommitStall->notify(inst);
708
709            DPRINTF(Commit,"[tid:%i]: Can't commit, Instruction [sn:%lli] PC "
710                    "%s is head of ROB and not ready\n",
711                    tid, inst->seqNum, inst->pcState());
712        }
713
714        DPRINTF(Commit, "[tid:%i]: ROB has %d insts & %d free entries.\n",
715                tid, rob->countInsts(tid), rob->numFreeEntries(tid));
716    }
717
718
719    if (wroteToTimeBuffer) {
720        DPRINTF(Activity, "Activity This Cycle.\n");
721        cpu->activityThisCycle();
722    }
723
724    updateStatus();
725}
726
727template <class Impl>
728void
729DefaultCommit<Impl>::handleInterrupt()
730{
731    // Verify that we still have an interrupt to handle
732    if (!cpu->checkInterrupts(cpu->tcBase(0))) {
733        DPRINTF(Commit, "Pending interrupt is cleared by master before "
734                "it got handled. Restart fetching from the orig path.\n");
735        toIEW->commitInfo[0].clearInterrupt = true;
736        interrupt = NoFault;
737        avoidQuiesceLiveLock = true;
738        return;
739    }
740
741    // Wait until all in flight instructions are finished before enterring
742    // the interrupt.
743    if (canHandleInterrupts && cpu->instList.empty()) {
744        // Squash or record that I need to squash this cycle if
745        // an interrupt needed to be handled.
746        DPRINTF(Commit, "Interrupt detected.\n");
747
748        // Clear the interrupt now that it's going to be handled
749        toIEW->commitInfo[0].clearInterrupt = true;
750
751        assert(!thread[0]->noSquashFromTC);
752        thread[0]->noSquashFromTC = true;
753
754        if (cpu->checker) {
755            cpu->checker->handlePendingInt();
756        }
757
758        // CPU will handle interrupt. Note that we ignore the local copy of
759        // interrupt. This is because the local copy may no longer be the
760        // interrupt that the interrupt controller thinks is being handled.
761        cpu->processInterrupts(cpu->getInterrupts());
762
763        thread[0]->noSquashFromTC = false;
764
765        commitStatus[0] = TrapPending;
766
767        interrupt = NoFault;
768
769        // Generate trap squash event.
770        generateTrapEvent(0, interrupt);
771
772        avoidQuiesceLiveLock = false;
773    } else {
774        DPRINTF(Commit, "Interrupt pending: instruction is %sin "
775                "flight, ROB is %sempty\n",
776                canHandleInterrupts ? "not " : "",
777                cpu->instList.empty() ? "" : "not " );
778    }
779}
780
781template <class Impl>
782void
783DefaultCommit<Impl>::propagateInterrupt()
784{
785    // Don't propagate intterupts if we are currently handling a trap or
786    // in draining and the last observable instruction has been committed.
787    if (commitStatus[0] == TrapPending || interrupt || trapSquash[0] ||
788            tcSquash[0] || drainImminent)
789        return;
790
791    // Process interrupts if interrupts are enabled, not in PAL
792    // mode, and no other traps or external squashes are currently
793    // pending.
794    // @todo: Allow other threads to handle interrupts.
795
796    // Get any interrupt that happened
797    interrupt = cpu->getInterrupts();
798
799    // Tell fetch that there is an interrupt pending.  This
800    // will make fetch wait until it sees a non PAL-mode PC,
801    // at which point it stops fetching instructions.
802    if (interrupt != NoFault)
803        toIEW->commitInfo[0].interruptPending = true;
804}
805
806template <class Impl>
807void
808DefaultCommit<Impl>::commit()
809{
810    if (FullSystem) {
811        // Check if we have a interrupt and get read to handle it
812        if (cpu->checkInterrupts(cpu->tcBase(0)))
813            propagateInterrupt();
814    }
815
816    ////////////////////////////////////
817    // Check for any possible squashes, handle them first
818    ////////////////////////////////////
819    list<ThreadID>::iterator threads = activeThreads->begin();
820    list<ThreadID>::iterator end = activeThreads->end();
821
822    int num_squashing_threads = 0;
823
824    while (threads != end) {
825        ThreadID tid = *threads++;
826
827        // Not sure which one takes priority.  I think if we have
828        // both, that's a bad sign.
829        if (trapSquash[tid]) {
830            assert(!tcSquash[tid]);
831            squashFromTrap(tid);
832
833            // If the thread is trying to exit (i.e., an exit syscall was
834            // executed), this trapSquash was originated by the exit
835            // syscall earlier. In this case, schedule an exit event in
836            // the next cycle to fully terminate this thread
837            if (cpu->isThreadExiting(tid))
838                cpu->scheduleThreadExitEvent(tid);
839        } else if (tcSquash[tid]) {
840            assert(commitStatus[tid] != TrapPending);
841            squashFromTC(tid);
842        } else if (commitStatus[tid] == SquashAfterPending) {
843            // A squash from the previous cycle of the commit stage (i.e.,
844            // commitInsts() called squashAfter) is pending. Squash the
845            // thread now.
846            squashFromSquashAfter(tid);
847        }
848
849        // Squashed sequence number must be older than youngest valid
850        // instruction in the ROB. This prevents squashes from younger
851        // instructions overriding squashes from older instructions.
852        if (fromIEW->squash[tid] &&
853            commitStatus[tid] != TrapPending &&
854            fromIEW->squashedSeqNum[tid] <= youngestSeqNum[tid]) {
855
856            if (fromIEW->mispredictInst[tid]) {
857                DPRINTF(Commit,
858                    "[tid:%i]: Squashing due to branch mispred PC:%#x [sn:%i]\n",
859                    tid,
860                    fromIEW->mispredictInst[tid]->instAddr(),
861                    fromIEW->squashedSeqNum[tid]);
862            } else {
863                DPRINTF(Commit,
864                    "[tid:%i]: Squashing due to order violation [sn:%i]\n",
865                    tid, fromIEW->squashedSeqNum[tid]);
866            }
867
868            DPRINTF(Commit, "[tid:%i]: Redirecting to PC %#x\n",
869                    tid,
870                    fromIEW->pc[tid].nextInstAddr());
871
872            commitStatus[tid] = ROBSquashing;
873
874            // If we want to include the squashing instruction in the squash,
875            // then use one older sequence number.
876            InstSeqNum squashed_inst = fromIEW->squashedSeqNum[tid];
877
878            if (fromIEW->includeSquashInst[tid]) {
879                squashed_inst--;
880            }
881
882            // All younger instructions will be squashed. Set the sequence
883            // number as the youngest instruction in the ROB.
884            youngestSeqNum[tid] = squashed_inst;
885
886            rob->squash(squashed_inst, tid);
887            changedROBNumEntries[tid] = true;
888
889            toIEW->commitInfo[tid].doneSeqNum = squashed_inst;
890
891            toIEW->commitInfo[tid].squash = true;
892
893            // Send back the rob squashing signal so other stages know that
894            // the ROB is in the process of squashing.
895            toIEW->commitInfo[tid].robSquashing = true;
896
897            toIEW->commitInfo[tid].mispredictInst =
898                fromIEW->mispredictInst[tid];
899            toIEW->commitInfo[tid].branchTaken =
900                fromIEW->branchTaken[tid];
901            toIEW->commitInfo[tid].squashInst =
902                                    rob->findInst(tid, squashed_inst);
903            if (toIEW->commitInfo[tid].mispredictInst) {
904                if (toIEW->commitInfo[tid].mispredictInst->isUncondCtrl()) {
905                     toIEW->commitInfo[tid].branchTaken = true;
906                }
907                ++branchMispredicts;
908            }
909
910            toIEW->commitInfo[tid].pc = fromIEW->pc[tid];
911        }
912
913        if (commitStatus[tid] == ROBSquashing) {
914            num_squashing_threads++;
915        }
916    }
917
918    // If commit is currently squashing, then it will have activity for the
919    // next cycle. Set its next status as active.
920    if (num_squashing_threads) {
921        _nextStatus = Active;
922    }
923
924    if (num_squashing_threads != numThreads) {
925        // If we're not currently squashing, then get instructions.
926        getInsts();
927
928        // Try to commit any instructions.
929        commitInsts();
930    }
931
932    //Check for any activity
933    threads = activeThreads->begin();
934
935    while (threads != end) {
936        ThreadID tid = *threads++;
937
938        if (changedROBNumEntries[tid]) {
939            toIEW->commitInfo[tid].usedROB = true;
940            toIEW->commitInfo[tid].freeROBEntries = rob->numFreeEntries(tid);
941
942            wroteToTimeBuffer = true;
943            changedROBNumEntries[tid] = false;
944            if (rob->isEmpty(tid))
945                checkEmptyROB[tid] = true;
946        }
947
948        // ROB is only considered "empty" for previous stages if: a)
949        // ROB is empty, b) there are no outstanding stores, c) IEW
950        // stage has received any information regarding stores that
951        // committed.
952        // c) is checked by making sure to not consider the ROB empty
953        // on the same cycle as when stores have been committed.
954        // @todo: Make this handle multi-cycle communication between
955        // commit and IEW.
956        if (checkEmptyROB[tid] && rob->isEmpty(tid) &&
957            !iewStage->hasStoresToWB(tid) && !committedStores[tid]) {
958            checkEmptyROB[tid] = false;
959            toIEW->commitInfo[tid].usedROB = true;
960            toIEW->commitInfo[tid].emptyROB = true;
961            toIEW->commitInfo[tid].freeROBEntries = rob->numFreeEntries(tid);
962            wroteToTimeBuffer = true;
963        }
964
965    }
966}
967
968template <class Impl>
969void
970DefaultCommit<Impl>::commitInsts()
971{
972    ////////////////////////////////////
973    // Handle commit
974    // Note that commit will be handled prior to putting new
975    // instructions in the ROB so that the ROB only tries to commit
976    // instructions it has in this current cycle, and not instructions
977    // it is writing in during this cycle.  Can't commit and squash
978    // things at the same time...
979    ////////////////////////////////////
980
981    DPRINTF(Commit, "Trying to commit instructions in the ROB.\n");
982
983    unsigned num_committed = 0;
984
985    DynInstPtr head_inst;
986
987    // Commit as many instructions as possible until the commit bandwidth
988    // limit is reached, or it becomes impossible to commit any more.
989    while (num_committed < commitWidth) {
990        // Check for any interrupt that we've already squashed for
991        // and start processing it.
992        if (interrupt != NoFault)
993            handleInterrupt();
994
995        ThreadID commit_thread = getCommittingThread();
996
997        if (commit_thread == -1 || !rob->isHeadReady(commit_thread))
998            break;
999
1000        head_inst = rob->readHeadInst(commit_thread);
1001
1002        ThreadID tid = head_inst->threadNumber;
1003
1004        assert(tid == commit_thread);
1005
1006        DPRINTF(Commit, "Trying to commit head instruction, [sn:%i] [tid:%i]\n",
1007                head_inst->seqNum, tid);
1008
1009        // If the head instruction is squashed, it is ready to retire
1010        // (be removed from the ROB) at any time.
1011        if (head_inst->isSquashed()) {
1012
1013            DPRINTF(Commit, "Retiring squashed instruction from "
1014                    "ROB.\n");
1015
1016            rob->retireHead(commit_thread);
1017
1018            ++commitSquashedInsts;
1019            // Notify potential listeners that this instruction is squashed
1020            ppSquash->notify(head_inst);
1021
1022            // Record that the number of ROB entries has changed.
1023            changedROBNumEntries[tid] = true;
1024        } else {
1025            pc[tid] = head_inst->pcState();
1026
1027            // Increment the total number of non-speculative instructions
1028            // executed.
1029            // Hack for now: it really shouldn't happen until after the
1030            // commit is deemed to be successful, but this count is needed
1031            // for syscalls.
1032            thread[tid]->funcExeInst++;
1033
1034            // Try to commit the head instruction.
1035            bool commit_success = commitHead(head_inst, num_committed);
1036
1037            if (commit_success) {
1038                ++num_committed;
1039                statCommittedInstType[tid][head_inst->opClass()]++;
1040                ppCommit->notify(head_inst);
1041
1042                changedROBNumEntries[tid] = true;
1043
1044                // Set the doneSeqNum to the youngest committed instruction.
1045                toIEW->commitInfo[tid].doneSeqNum = head_inst->seqNum;
1046
1047                if (tid == 0) {
1048                    canHandleInterrupts =  (!head_inst->isDelayedCommit()) &&
1049                                           ((THE_ISA != ALPHA_ISA) ||
1050                                             (!(pc[0].instAddr() & 0x3)));
1051                }
1052
1053                // at this point store conditionals should either have
1054                // been completed or predicated false
1055                assert(!head_inst->isStoreConditional() ||
1056                       head_inst->isCompleted() ||
1057                       !head_inst->readPredicate());
1058
1059                // Updates misc. registers.
1060                head_inst->updateMiscRegs();
1061
1062                // Check instruction execution if it successfully commits and
1063                // is not carrying a fault.
1064                if (cpu->checker) {
1065                    cpu->checker->verify(head_inst);
1066                }
1067
1068                cpu->traceFunctions(pc[tid].instAddr());
1069
1070                TheISA::advancePC(pc[tid], head_inst->staticInst);
1071
1072                // Keep track of the last sequence number commited
1073                lastCommitedSeqNum[tid] = head_inst->seqNum;
1074
1075                // If this is an instruction that doesn't play nicely with
1076                // others squash everything and restart fetch
1077                if (head_inst->isSquashAfter())
1078                    squashAfter(tid, head_inst);
1079
1080                if (drainPending) {
1081                    if (pc[tid].microPC() == 0 && interrupt == NoFault &&
1082                        !thread[tid]->trapPending) {
1083                        // Last architectually committed instruction.
1084                        // Squash the pipeline, stall fetch, and use
1085                        // drainImminent to disable interrupts
1086                        DPRINTF(Drain, "Draining: %i:%s\n", tid, pc[tid]);
1087                        squashAfter(tid, head_inst);
1088                        cpu->commitDrained(tid);
1089                        drainImminent = true;
1090                    }
1091                }
1092
1093                bool onInstBoundary = !head_inst->isMicroop() ||
1094                                      head_inst->isLastMicroop() ||
1095                                      !head_inst->isDelayedCommit();
1096
1097                if (onInstBoundary) {
1098                    int count = 0;
1099                    Addr oldpc;
1100                    // Make sure we're not currently updating state while
1101                    // handling PC events.
1102                    assert(!thread[tid]->noSquashFromTC &&
1103                           !thread[tid]->trapPending);
1104                    do {
1105                        oldpc = pc[tid].instAddr();
1106                        cpu->system->pcEventQueue.service(thread[tid]->getTC());
1107                        count++;
1108                    } while (oldpc != pc[tid].instAddr());
1109                    if (count > 1) {
1110                        DPRINTF(Commit,
1111                                "PC skip function event, stopping commit\n");
1112                        break;
1113                    }
1114                }
1115
1116                // Check if an instruction just enabled interrupts and we've
1117                // previously had an interrupt pending that was not handled
1118                // because interrupts were subsequently disabled before the
1119                // pipeline reached a place to handle the interrupt. In that
1120                // case squash now to make sure the interrupt is handled.
1121                //
1122                // If we don't do this, we might end up in a live lock situation
1123                if (!interrupt && avoidQuiesceLiveLock &&
1124                    onInstBoundary && cpu->checkInterrupts(cpu->tcBase(0)))
1125                    squashAfter(tid, head_inst);
1126            } else {
1127                DPRINTF(Commit, "Unable to commit head instruction PC:%s "
1128                        "[tid:%i] [sn:%i].\n",
1129                        head_inst->pcState(), tid ,head_inst->seqNum);
1130                break;
1131            }
1132        }
1133    }
1134
1135    DPRINTF(CommitRate, "%i\n", num_committed);
1136    numCommittedDist.sample(num_committed);
1137
1138    if (num_committed == commitWidth) {
1139        commitEligibleSamples++;
1140    }
1141}
1142
1143template <class Impl>
1144bool
1145DefaultCommit<Impl>::commitHead(const DynInstPtr &head_inst, unsigned inst_num)
1146{
1147    assert(head_inst);
1148
1149    ThreadID tid = head_inst->threadNumber;
1150
1151    // If the instruction is not executed yet, then it will need extra
1152    // handling.  Signal backwards that it should be executed.
1153    if (!head_inst->isExecuted()) {
1154        // Keep this number correct.  We have not yet actually executed
1155        // and committed this instruction.
1156        thread[tid]->funcExeInst--;
1157
1158        // Make sure we are only trying to commit un-executed instructions we
1159        // think are possible.
1160        assert(head_inst->isNonSpeculative() || head_inst->isStoreConditional()
1161               || head_inst->isMemBarrier() || head_inst->isWriteBarrier() ||
1162               (head_inst->isLoad() && head_inst->strictlyOrdered()));
1163
1164        DPRINTF(Commit, "Encountered a barrier or non-speculative "
1165                "instruction [sn:%lli] at the head of the ROB, PC %s.\n",
1166                head_inst->seqNum, head_inst->pcState());
1167
1168        if (inst_num > 0 || iewStage->hasStoresToWB(tid)) {
1169            DPRINTF(Commit, "Waiting for all stores to writeback.\n");
1170            return false;
1171        }
1172
1173        toIEW->commitInfo[tid].nonSpecSeqNum = head_inst->seqNum;
1174
1175        // Change the instruction so it won't try to commit again until
1176        // it is executed.
1177        head_inst->clearCanCommit();
1178
1179        if (head_inst->isLoad() && head_inst->strictlyOrdered()) {
1180            DPRINTF(Commit, "[sn:%lli]: Strictly ordered load, PC %s.\n",
1181                    head_inst->seqNum, head_inst->pcState());
1182            toIEW->commitInfo[tid].strictlyOrdered = true;
1183            toIEW->commitInfo[tid].strictlyOrderedLoad = head_inst;
1184        } else {
1185            ++commitNonSpecStalls;
1186        }
1187
1188        return false;
1189    }
1190
1191    if (head_inst->isThreadSync()) {
1192        // Not handled for now.
1193        panic("Thread sync instructions are not handled yet.\n");
1194    }
1195
1196    // Check if the instruction caused a fault.  If so, trap.
1197    Fault inst_fault = head_inst->getFault();
1198
1199    // Stores mark themselves as completed.
1200    if (!head_inst->isStore() && inst_fault == NoFault) {
1201        head_inst->setCompleted();
1202    }
1203
1204    if (inst_fault != NoFault) {
1205        DPRINTF(Commit, "Inst [sn:%lli] PC %s has a fault\n",
1206                head_inst->seqNum, head_inst->pcState());
1207
1208        if (iewStage->hasStoresToWB(tid) || inst_num > 0) {
1209            DPRINTF(Commit, "Stores outstanding, fault must wait.\n");
1210            return false;
1211        }
1212
1213        head_inst->setCompleted();
1214
1215        // If instruction has faulted, let the checker execute it and
1216        // check if it sees the same fault and control flow.
1217        if (cpu->checker) {
1218            // Need to check the instruction before its fault is processed
1219            cpu->checker->verify(head_inst);
1220        }
1221
1222        assert(!thread[tid]->noSquashFromTC);
1223
1224        // Mark that we're in state update mode so that the trap's
1225        // execution doesn't generate extra squashes.
1226        thread[tid]->noSquashFromTC = true;
1227
1228        // Execute the trap.  Although it's slightly unrealistic in
1229        // terms of timing (as it doesn't wait for the full timing of
1230        // the trap event to complete before updating state), it's
1231        // needed to update the state as soon as possible.  This
1232        // prevents external agents from changing any specific state
1233        // that the trap need.
1234        cpu->trap(inst_fault, tid,
1235                  head_inst->notAnInst() ?
1236                      StaticInst::nullStaticInstPtr :
1237                      head_inst->staticInst);
1238
1239        // Exit state update mode to avoid accidental updating.
1240        thread[tid]->noSquashFromTC = false;
1241
1242        commitStatus[tid] = TrapPending;
1243
1244        DPRINTF(Commit, "Committing instruction with fault [sn:%lli]\n",
1245            head_inst->seqNum);
1246        if (head_inst->traceData) {
1247            if (DTRACE(ExecFaulting)) {
1248                head_inst->traceData->setFetchSeq(head_inst->seqNum);
1249                head_inst->traceData->setCPSeq(thread[tid]->numOp);
1250                head_inst->traceData->dump();
1251            }
1252            delete head_inst->traceData;
1253            head_inst->traceData = NULL;
1254        }
1255
1256        // Generate trap squash event.
1257        generateTrapEvent(tid, inst_fault);
1258        return false;
1259    }
1260
1261    updateComInstStats(head_inst);
1262
1263    if (FullSystem) {
1264        if (thread[tid]->profile) {
1265            thread[tid]->profilePC = head_inst->instAddr();
1266            ProfileNode *node = thread[tid]->profile->consume(
1267                    thread[tid]->getTC(), head_inst->staticInst);
1268
1269            if (node)
1270                thread[tid]->profileNode = node;
1271        }
1272        if (CPA::available()) {
1273            if (head_inst->isControl()) {
1274                ThreadContext *tc = thread[tid]->getTC();
1275                CPA::cpa()->swAutoBegin(tc, head_inst->nextInstAddr());
1276            }
1277        }
1278    }
1279    DPRINTF(Commit, "Committing instruction with [sn:%lli] PC %s\n",
1280            head_inst->seqNum, head_inst->pcState());
1281    if (head_inst->traceData) {
1282        head_inst->traceData->setFetchSeq(head_inst->seqNum);
1283        head_inst->traceData->setCPSeq(thread[tid]->numOp);
1284        head_inst->traceData->dump();
1285        delete head_inst->traceData;
1286        head_inst->traceData = NULL;
1287    }
1288    if (head_inst->isReturn()) {
1289        DPRINTF(Commit,"Return Instruction Committed [sn:%lli] PC %s \n",
1290                        head_inst->seqNum, head_inst->pcState());
1291    }
1292
1293    // Update the commit rename map
1294    for (int i = 0; i < head_inst->numDestRegs(); i++) {
1295        renameMap[tid]->setEntry(head_inst->flattenedDestRegIdx(i),
1296                                 head_inst->renamedDestRegIdx(i));
1297    }
1298
1299    // Finally clear the head ROB entry.
1300    rob->retireHead(tid);
1301
1302#if TRACING_ON
1303    if (DTRACE(O3PipeView)) {
1304        head_inst->commitTick = curTick() - head_inst->fetchTick;
1305    }
1306#endif
1307
1308    // If this was a store, record it for this cycle.
1309    if (head_inst->isStore())
1310        committedStores[tid] = true;
1311
1312    // Return true to indicate that we have committed an instruction.
1313    return true;
1314}
1315
1316template <class Impl>
1317void
1318DefaultCommit<Impl>::getInsts()
1319{
1320    DPRINTF(Commit, "Getting instructions from Rename stage.\n");
1321
1322    // Read any renamed instructions and place them into the ROB.
1323    int insts_to_process = std::min((int)renameWidth, fromRename->size);
1324
1325    for (int inst_num = 0; inst_num < insts_to_process; ++inst_num) {
1326        const DynInstPtr &inst = fromRename->insts[inst_num];
1327        ThreadID tid = inst->threadNumber;
1328
1329        if (!inst->isSquashed() &&
1330            commitStatus[tid] != ROBSquashing &&
1331            commitStatus[tid] != TrapPending) {
1332            changedROBNumEntries[tid] = true;
1333
1334            DPRINTF(Commit, "Inserting PC %s [sn:%i] [tid:%i] into ROB.\n",
1335                    inst->pcState(), inst->seqNum, tid);
1336
1337            rob->insertInst(inst);
1338
1339            assert(rob->getThreadEntries(tid) <= rob->getMaxEntries(tid));
1340
1341            youngestSeqNum[tid] = inst->seqNum;
1342        } else {
1343            DPRINTF(Commit, "Instruction PC %s [sn:%i] [tid:%i] was "
1344                    "squashed, skipping.\n",
1345                    inst->pcState(), inst->seqNum, tid);
1346        }
1347    }
1348}
1349
1350template <class Impl>
1351void
1352DefaultCommit<Impl>::markCompletedInsts()
1353{
1354    // Grab completed insts out of the IEW instruction queue, and mark
1355    // instructions completed within the ROB.
1356    for (int inst_num = 0; inst_num < fromIEW->size; ++inst_num) {
1357        assert(fromIEW->insts[inst_num]);
1358        if (!fromIEW->insts[inst_num]->isSquashed()) {
1359            DPRINTF(Commit, "[tid:%i]: Marking PC %s, [sn:%lli] ready "
1360                    "within ROB.\n",
1361                    fromIEW->insts[inst_num]->threadNumber,
1362                    fromIEW->insts[inst_num]->pcState(),
1363                    fromIEW->insts[inst_num]->seqNum);
1364
1365            // Mark the instruction as ready to commit.
1366            fromIEW->insts[inst_num]->setCanCommit();
1367        }
1368    }
1369}
1370
1371template <class Impl>
1372void
1373DefaultCommit<Impl>::updateComInstStats(const DynInstPtr &inst)
1374{
1375    ThreadID tid = inst->threadNumber;
1376
1377    if (!inst->isMicroop() || inst->isLastMicroop())
1378        instsCommitted[tid]++;
1379    opsCommitted[tid]++;
1380
1381    // To match the old model, don't count nops and instruction
1382    // prefetches towards the total commit count.
1383    if (!inst->isNop() && !inst->isInstPrefetch()) {
1384        cpu->instDone(tid, inst);
1385    }
1386
1387    //
1388    //  Control Instructions
1389    //
1390    if (inst->isControl())
1391        statComBranches[tid]++;
1392
1393    //
1394    //  Memory references
1395    //
1396    if (inst->isMemRef()) {
1397        statComRefs[tid]++;
1398
1399        if (inst->isLoad()) {
1400            statComLoads[tid]++;
1401        }
1402    }
1403
1404    if (inst->isMemBarrier()) {
1405        statComMembars[tid]++;
1406    }
1407
1408    // Integer Instruction
1409    if (inst->isInteger())
1410        statComInteger[tid]++;
1411
1412    // Floating Point Instruction
1413    if (inst->isFloating())
1414        statComFloating[tid]++;
1415    // Vector Instruction
1416    if (inst->isVector())
1417        statComVector[tid]++;
1418
1419    // Function Calls
1420    if (inst->isCall())
1421        statComFunctionCalls[tid]++;
1422
1423}
1424
1425////////////////////////////////////////
1426//                                    //
1427//  SMT COMMIT POLICY MAINTAINED HERE //
1428//                                    //
1429////////////////////////////////////////
1430template <class Impl>
1431ThreadID
1432DefaultCommit<Impl>::getCommittingThread()
1433{
1434    if (numThreads > 1) {
1435        switch (commitPolicy) {
1436
1437          case CommitPolicy::Aggressive:
1438            //If Policy is Aggressive, commit will call
1439            //this function multiple times per
1440            //cycle
1441            return oldestReady();
1442
1443          case CommitPolicy::RoundRobin:
1444            return roundRobin();
1445
1446          case CommitPolicy::OldestReady:
1447            return oldestReady();
1448
1449          default:
1450            return InvalidThreadID;
1451        }
1452    } else {
1453        assert(!activeThreads->empty());
1454        ThreadID tid = activeThreads->front();
1455
1456        if (commitStatus[tid] == Running ||
1457            commitStatus[tid] == Idle ||
1458            commitStatus[tid] == FetchTrapPending) {
1459            return tid;
1460        } else {
1461            return InvalidThreadID;
1462        }
1463    }
1464}
1465
1466template<class Impl>
1467ThreadID
1468DefaultCommit<Impl>::roundRobin()
1469{
1470    list<ThreadID>::iterator pri_iter = priority_list.begin();
1471    list<ThreadID>::iterator end      = priority_list.end();
1472
1473    while (pri_iter != end) {
1474        ThreadID tid = *pri_iter;
1475
1476        if (commitStatus[tid] == Running ||
1477            commitStatus[tid] == Idle ||
1478            commitStatus[tid] == FetchTrapPending) {
1479
1480            if (rob->isHeadReady(tid)) {
1481                priority_list.erase(pri_iter);
1482                priority_list.push_back(tid);
1483
1484                return tid;
1485            }
1486        }
1487
1488        pri_iter++;
1489    }
1490
1491    return InvalidThreadID;
1492}
1493
1494template<class Impl>
1495ThreadID
1496DefaultCommit<Impl>::oldestReady()
1497{
1498    unsigned oldest = 0;
1499    bool first = true;
1500
1501    list<ThreadID>::iterator threads = activeThreads->begin();
1502    list<ThreadID>::iterator end = activeThreads->end();
1503
1504    while (threads != end) {
1505        ThreadID tid = *threads++;
1506
1507        if (!rob->isEmpty(tid) &&
1508            (commitStatus[tid] == Running ||
1509             commitStatus[tid] == Idle ||
1510             commitStatus[tid] == FetchTrapPending)) {
1511
1512            if (rob->isHeadReady(tid)) {
1513
1514                const DynInstPtr &head_inst = rob->readHeadInst(tid);
1515
1516                if (first) {
1517                    oldest = tid;
1518                    first = false;
1519                } else if (head_inst->seqNum < oldest) {
1520                    oldest = tid;
1521                }
1522            }
1523        }
1524    }
1525
1526    if (!first) {
1527        return oldest;
1528    } else {
1529        return InvalidThreadID;
1530    }
1531}
1532
1533#endif//__CPU_O3_COMMIT_IMPL_HH__
1534