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