analyze-xiangshan-kunminghu · git:20260721.1f8fa49 · 2026-07-21 · sha256 186a6e5b5e7ae48e

analyze-xiangshan-kunminghu git:20260721.1f8fa49A

Immutable. This exact content is served forever at /api/v1/blob/186a6e5b5e7ae48e.

---
name: analyze-xiangshan-kunminghu
description: Analyze OpenXiangShan Kunminghu source and related design/course code. Use for code-grounded module walkthroughs, branch comparison, signal/FSM/dataflow/storage analysis, frontend/backend pipeline tracing, predictor/cache/MMU/MMIO/AXI/AIA/IOPMP/difftest behavior, timing/throughput, exceptions, replay/redirect, and verification. Include cross-page/cache-line/MMIO analysis plus Mermaid and WaveDrom diagrams.
---

# Analyze XiangShan Kunminghu

## Objective

Use this skill to produce code-grounded explanations of XiangShan Kunminghu modules, including branch-to-branch module comparisons when requested. Always obtain XiangShan source code directly from `https://github.com/OpenXiangShan/XiangShan.git` unless the user explicitly provides a local path. Default single-branch analysis to branch `kunminghu-v2` unless the user explicitly asks for another branch or commit. For comparison analysis, require two branch/commit names and one or more modules/paths from the user; if any of these are missing, ask for the missing branch/module fields before analyzing. If the prompt contains a conflicting branch/path, state the source URL and branch/commit being analyzed before explaining.

Primary source roots:
- Weekly sync helper: `scripts/weekly_sync.py` and `references/weekly-sync.md`
- Analysis output saver: `scripts/save_analysis.py` and `references/analysis-output.md`
- Tutorial Markdown normalizer: `scripts/tutorialize_frontend_docs.py` and `references/tutorial-output.md`
- Predictor paper search: `paper-search-agent-mcp` via `mcp__paper_search_agent`, plus `references/predictor-papers.md`
- AIA/IOPMP/AXI analysis: `references/aia-iopmp-axi.md`
- Difftest signal and architectural-state analysis: `references/difftest.md`
- Verification special attention: `references/verification-special-attention.md`, derived from `tools/verification-driver/skills`
- Design Doc to source traceability: `references/design-doc-code-trace.md`
- Cross-boundary analysis: `references/cross-boundary-analysis.md`
- VS Code waveform display: `references/vscode-waveform.md`
- XiangShan source: `https://github.com/OpenXiangShan/XiangShan.git`, source root `src/main/scala/xiangshan`
- XiangShan Design Doc: `https://github.com/OpenXiangShan/XiangShan-Design-Doc.git`
- XiangShanLab course repo: `https://github.com/OpenXiangShan/XiangShanLab.git`
- XSCache repo: `https://github.com/OpenXiangShan/XSCache.git`
- Course background: XiangShanLab course system 4 implementation docs, especially superscalar/out-of-order basics and XiangShan high-performance out-of-order pipeline docs, plus course system 5 dynamic instruction execution docs
- Required analysis style: answer every module through `who`, `why`, `how`, `from what`, and `to what`

## Workflow

Before step 1, read `references/weekly-sync.md` and run `scripts/weekly_sync.py` unless the user explicitly asks not to sync. This performs a 7-day guarded sync check for local Design Doc, XiangShanLab, and course analysis directories; XiangShan source itself must be fetched or inspected directly from `https://github.com/OpenXiangShan/XiangShan.git`. The sync helper must never reset, clean, or overwrite dirty worktrees.
1. Locate the requested module by fetching or inspecting `https://github.com/OpenXiangShan/XiangShan.git` at the requested branch/commit. Use local XiangShan source only when the user explicitly provides a local path or when GitHub/network access is unavailable and the fallback is clearly stated.
2. Locate matching foundational theory material before code analysis. Read `references/xiangshanlab-course-map.md` and `references/theory-code-mapping.md`, then inspect relevant XiangShanLab superscalar/out-of-order course markdown when available.
3. Locate matching design documentation before explaining broad intent. Read `references/design-doc-map.md` and `references/design-doc-code-trace.md`, then inspect the relevant Design Doc markdown/figures.
4. For predictor analysis, read `references/predictor-papers.md` and use `paper-search-agent-mcp` (`mcp__paper_search_agent.search_papers`) to find the relevant branch-prediction paper(s) before explaining algorithm principles.
5. Read the real Scala/Chisel files from `https://github.com/OpenXiangShan/XiangShan.git` before explaining implementation. When Design Doc material is used, map every load-bearing claim, figure edge, table row, stage, parameter, and interface assumption to effective source lines before presenting it as behavior. Do not infer behavior from names or documentation alone. Record the analyzed source commit (`git rev-parse HEAD` for local checkouts, or the GitHub commit/branch SHA when browsing remote source). Use line-numbered reads such as `nl -ba` or editor line references so every algorithm, port, connection, and datapath claim can cite exact Chisel lines.
6. Identify the enclosing subsystem and load the matching reference:
   - Theory-to-code mapping: read `references/theory-code-mapping.md`
   - XiangShanLab course navigation: read `references/xiangshanlab-course-map.md`
   - Backend pipeline: read `references/backend.md`
   - Frontend fetch and prediction: read `references/frontend.md`
   - Predictor paper search and algorithm principles: read `references/predictor-papers.md` for branch/target/indirect/RAS/statistical-corrector predictor analysis
   - chiselAIA/chiselIOPMP/AXI bus behavior: read `references/aia-iopmp-axi.md` for APLIC/IMSIC, IOPMP, AXI master/slave, and AXI protocol control-signal analysis
   - Memory/cache instruction behavior: read `references/mem-cache.md`
   - XSCache cache subsystem: read `references/xscache.md`
   - Load/store instruction taxonomy: read `references/load-store-instruction-taxonomy.md`
   - Instruction latency and throughput: read `references/instruction-latency-throughput.md`
   - Algorithms, FSMs, control path, and data path: read `references/algorithm-control-dataflow.md`
   - Exceptions, interrupts, debug, and privilege: read `references/exception-debug-privilege.md`
   - Difftest architectural-state, cache-state, queue-state, exception, interrupt, and memory-address signals: read `references/difftest.md`
   - Queue and buffer capacity logic: read `references/queue-buffer-capacity.md`
   - Mermaid and waveform-draw timing diagrams: read `references/diagrams.md`
   - Output structure and question checklist: read `references/analysis-template.md`
   - Design Doc to source traceability: always read `references/design-doc-code-trace.md` when Design Doc content is consulted; include both repository baselines and a claim-to-source matrix
   - Weekly repository sync: read `references/weekly-sync.md` before source inspection; this syncs local docs/course inputs, not the authoritative XiangShan source
   - Analysis output saving: read `references/analysis-output.md` before writing generated Markdown
   - Tutorial-oriented Markdown output: read `references/tutorial-output.md` and run `scripts/tutorialize_frontend_docs.py` after generating a Frontend document set or when the user asks to reorganize existing analysis into a tutorial
   - Verification special attention: always read `references/verification-special-attention.md` before writing; select the applicable predictor, BPU, FTQ, queue, RAS, ICache, exception/virtualization, conflict, FSM, forward-progress, and performance rows
   - Cross-boundary analysis: always read `references/cross-boundary-analysis.md` for any fetch, memory, cache, MMU, bus, AXI, MMIO, instruction, or address-range analysis
   - VS Code waveform display: read `references/vscode-waveform.md` before generating timing diagrams or explaining how to preview them
7. Separate theory, design intent from effective code:
   - Use XiangShanLab course docs to define architecture concepts such as superscalar issue, hazards, register renaming, Tomasulo/scoreboard ideas, issue queues, bypass, physical registers, ROB, and dynamic instruction execution.
   - Use Design Doc/course implementation docs to describe motivation and intended XiangShan architecture.
   - Use active source files, instantiated modules, actual IO connections, and parameter values to describe what the implementation really does.
   - If theory/docs and code disagree or a concept is implemented differently, state the difference and prefer code for behavior.
8. Trace interfaces first: `IO(...)`, bundle classes, Decoupled/Valid handshakes, difftest bundles/events, AXI/TL/APB channels, redirect/flush signals, wakeup/writeback channels, interrupt lines, MMU/cache request-response channels, and ROB/FTQ/LSQ pointers. For AXI, explicitly identify master/slave role and AW/W/B/AR/R channel direction before explaining behavior.
9. For memory/cache/XSCache targets, build a per-stage pipeline map before summarizing behavior. For every visible stage (`s0/s1/s2`, request, TLB, tag/meta, data, miss, refill, writeback, replay, commit, or named FSM stage), state what work the stage performs, which payload/control registers it owns, what index/address/allocation decision is computed there, what can stall/flush/replay/cancel it, and what leaves the stage.
10. Trace index and address calculations before summarizing any table, array, queue, cache, bank, entry, pointer, allocation slot, free-list slot, MSHR entry, replay entry, PTW entry, victim way, or selector access. For every index, explain exactly how it is computed from fields/signals/parameters, which bits are used, how bank/set/way/entry slices are formed, how wraparound or pointer arithmetic works, how the allocation/free algorithm chooses the index, and where the computed index is consumed. Include first-cycle or reset-time index behavior when registers or counters are involved.
11. Trace state updates: `RegInit`, `RegEnable`, `RegNext`, `SyncDataModule`, SRAM/data arrays, queues, tables, valid bits, pointers, snapshots, replay queues, FSM state registers, refill/writeback buffers, and replacement metadata. For every explicit FSM or implicit valid/status lifecycle, document reset state, state meaning, why the state exists, a concrete scenario that enters or uses the state, entry condition, transition condition, stage action, output action, blocking condition, and exit/clear condition. For every valid/status bit, explicitly state reset/initial value, set condition, clear condition, hold condition, flush/cancel condition, why the bit exists, an example transaction scenario, and all consumers that observe it. For every storage structure, analyze it through `update`, `release`, `replace`, and `search/read/probe`: the exact timing, enable/fire condition, index calculation, payload fields updated/read/released/replaced, valid-bit effect, conflict priority when multiple operations happen together, and downstream effect. For every read/write port on a storage structure, analyze conflict scenarios: same-cycle read/write same index, multiple writes same index, multiple reads contending for a limited port, read-after-write/write-after-read/write-after-write behavior, bypass/forwarding or assert behavior, and which request wins or stalls. For every queue/buffer, inspect empty/full/almost-full/allow-enqueue/allow-dequeue/backpressure logic.
12. Trace algorithms and paths: replacement, allocation/free index selection, arbitration, selection, prediction, replay, redirect, dependency, forwarding, merge/split, miss handling, permission checking, AIA interrupt delivery/priority, IOPMP permission match/deny, AXI address routing/outstanding/burst/response handling, exception/interrupt/debug/privilege checks, and exception priority algorithms. For every algorithm, port/interface, inter-module connection, and datapath segment, cite exact Chisel source line numbers and include a short core code snippet from the analyzed commit. For every key control signal or state transition that changes behavior, explain why it exists and give at least one concrete scenario, such as a stall, replay, redirect, miss, exception, full queue, conflicting request, probe, refill, or commit release. For each algorithm, describe how it works from initialization/reset, how the first real transaction/request is handled, all major cases/branches, tie or priority behavior, invalid/empty/full behavior, and how state evolves after each case. For every arbiter or priority selector, explicitly analyze the simultaneous-request scenario: all requesters that can assert together, request qualification, priority/age/round-robin rule, grant generation, ready/backpressure, losing request behavior, and same-cycle update effects.

12a. For every frontend branch predictor or predictor-like component (`BPU`/`Composer`, `Bim`/base table, `FTB`, `FauFTB`/uFTB, `Tage`, `SC`, `ITTAGE`, `RAS`/`newRAS`), add an `Algorithm Example Walkthrough` section. The walkthrough must use a concrete example input and state, such as a fetch PC, branch slot, folded/global history bits, table valid/tag/counter/useful state, RAS pointer/top state, FTQ update metadata, or redirect metadata. Step through lookup, selection, prediction response, update/training, allocation/replacement, and recovery/redirect effects as applicable. Each step must cite the source lines that implement the rule and explicitly state the example input, intermediate state changes, and output. If the component is not effective in the analyzed commit, still provide a non-effective example based on the commented/dead code and clearly label it as non-effective.

12b. For every frontend branch predictor or predictor-like component, add a `Stage-by-Stage Algorithm` section. Cover every effective prediction pipeline stage visible in the code (`s0`, `s1`, `s2`, `s3`, update stages, commit/update stage, and redirect/recovery stage when present). For each stage, state the concrete inputs entering the stage, table/queue/register accesses, index/tag/pointer calculations, hit/provider/target/direction selection, metadata captured, ready/valid/fire or stall behavior, state updates performed in that stage, and the output consumed by the next stage. Cite exact Chisel source lines for every stage rule. If a predictor has no effective code or is fully commented out, explicitly say so and map the effective replacement stage behavior.

12c. For frontend prediction analysis, add a `Redirect Signal Generation` section. Trace how redirect or override signals are produced, including BPU-level `s2_redirect`, `s3_redirect`, backend/FTQ redirect, and predictor-local recovery or cancel signals such as RAS `s3_cancel`, ITTAGE target override, FTB multi-hit/fall-through redirect causes, TAGE/SC direction override effects, and FauFTB/FTB false-hit reopen behavior. For every redirect-like signal, identify producer, exact source condition, stage, priority/interaction with flush, state repaired, downstream consumer, and a concrete example. If the predictor does not directly generate redirect, state how its output can cause BPU-level redirect.

12d. For frontend branch prediction analysis, add a `Predictor Relationship` section. Explain how `FauFTB`/uFTB, `FTB`, `Tage`, `SC`, `ITTAGE`, `RAS`/`newRAS`, `Bim`/base table, and `BPU`/`Composer` relate to each other in the effective predictor chain. Cover instantiation order, stage timing, which predictor supplies target, conditional direction, indirect target, return target, fall-through, and metadata, which predictor can override or refine another predictor, how `last_stage_meta`/FTQ update metadata connects the components, how update/training is fanned out or qualified, how redirect/recovery repairs shared history/RAS/FTQ state, and what happens when predictors disagree. Cite exact Chisel source lines for the chain construction, inter-predictor wiring, priority/mux selection, update fanout, and recovery paths. Include one concrete cross-predictor scenario, such as uFTB predicts a fall-through while FTB+TAGE later find a taken branch, TAGE direction is corrected by SC, ITTAGE overrides a JALR target, or RAS supplies a return target and is canceled by redirect.
13. Build a scenario mapping for every replay, redirect, conflict, contention, and resource empty/full path that exists in the requested module or changed diff. For each scenario, identify the trigger, competing requesters or blocked resource, exact signal condition, winner/loser behavior, state updates, pipeline/queue/cache effect, and downstream consumer. If a requested category is absent, state that it was searched and not found.
14. Generate diagrams after the trace is understood: one Mermaid data-path diagram, one Mermaid module-interface diagram, and one waveform-draw handshake timing diagram for every requested module that has Decoupled, Valid, pipeline-valid, request/response, enqueue/dequeue, grant/accept, or stall/backpressure behavior. Keep diagrams faithful to effective code; include only real modules, ports, queues, arrays, FSM states, and pipeline stages.
14a. For top-level or end-to-end analysis, always add a compact Mermaid module graph and a separate Mermaid pipeline-stage graph. Bundle related signals, keep each pair of modules to at most three edges, and never draw one edge per signal. If a readable graph would exceed that limit, split it into subgraphs such as `Frontend`, `Fetch/ICache`, `Backend`, `Memory/Cache`, and `Commit/Redirect`; connect subgraphs only with the minimum key interface edges. The pipeline graph must follow effective source stage names and show Frontend stages such as `F0/F1/F2/F3` when present, then Backend stages such as Decode/Rename/Dispatch/Issue/Execute/Writeback/Commit or the actual names proven by code. Do not replace the stage graph with a generic CPU pipeline.
15. For instruction, backend, memory, cache, or FU analysis, read `references/instruction-latency-throughput.md` and add a latency/throughput section. Derive latency from decode-to-commit path stages, FU/wrapper valid timing, memory/cache response timing, replay/exception paths, and writeback/commit timing. Derive throughput from issue width, FU counts, port counts, pipelining or busy/ready behavior, writeback arbitration, cache/MSHR/bank/queue resources, and backpressure. State whether each number is a code-proven fixed cycle count, a best-case bound, a steady-state initiation interval, a variable/miss-dependent bound, or unclear without elaboration/waveforms.
16. Save generated module analysis Markdown to the code-deep-dive course directory. Read `references/analysis-output.md` and use `scripts/save_analysis.py`; default destination is `xiangshan-course/docs/课程体系4:实现篇-香山高性能处理器微架构优化/中级-高性能香山处理器代码深入解析/` relative to `xiangshanlab_home`.
17. Explain only claims supported by code or cited design docs. If a signal source or sink is unclear, say what was found and what file should be inspected next.


## Branch Comparison Workflow

Use this mode when the user asks to compare two branches, versions, commits, or implementations of a module.

Required user inputs:
- Base branch/commit: the older, baseline, or left-side version.
- Target branch/commit: the newer, experiment, or right-side version.
- Module/path: one or more module names, Scala/Chisel files, or subsystem paths to compare.

If the user gives only one branch, only one side of the comparison, or no module, ask a concise clarification for the missing fields before fetching source. If the user does not define base/target direction but provides two branch names, preserve the user-provided order and label them explicitly.

Comparison procedure:
1. Resolve both branches/commits from `https://github.com/OpenXiangShan/XiangShan.git` or the user-provided local path. Record both exact commit SHAs.
2. Locate the requested module in both versions. If a file or module was renamed, moved, added, or deleted, identify the old and new paths and cite the evidence from `git diff --name-status`, `git log --follow`, or direct tree inspection.
3. Build a file set for comparison: primary module file, instantiated child modules whose interfaces changed, parameter definitions, bundle definitions, decode/CSR/config files when they affect the module, and test or elaboration hooks when relevant.
4. Generate a source diff for the selected file set only. Prefer `git diff <base>..<target> -- <paths>` for one checkout or `git diff --no-index` for two worktrees. Do not summarize repository-wide churn.
5. Treat each meaningful diff hunk as a code-analysis target, not a standalone text patch. For every changed hunk, recover the enclosing module/class/function, IO bundle, parameter owner, pipeline stage, storage structure, FSM, arbitration network, or algorithm context before explaining it.
6. Read line-numbered source from both versions for every behavior-changing difference. Cite both sides as `base file:line` and `target file:line`; include short core snippets from both sides when a behavior claim depends on changed code.
7. Classify every meaningful difference by impact area: public interface/IO, parameters, instantiation path, control path, data path, FSM/state lifecycle, storage structure, index/address calculation, arbitration/priority, exception/interrupt/debug/privilege, AXI/TL/APB protocol, memory/cache pipeline stage, predictor algorithm, or documentation-only/no effective behavior.
8. For every semantic change, apply the normal module-analysis principles from this skill: answer who owns/updates it, why it exists, how it works, from what signal/source it is derived, and to what consumer/effect it flows. Also analyze affected valid/ready/fire behavior, state set/clear/hold behavior, index/address calculation, storage update/release/replace/search behavior, and simultaneous-request arbitration when relevant.
9. Explain behavioral impact, not only text diff: what input scenario changes, which downstream module observes it, whether timing/backpressure/replay/flush/exception behavior changes, and whether compatibility or verification risk increases.
10. Separate mechanical changes from semantic changes. Treat formatting, rename-only, comment-only, and dead-code changes as low impact unless they change effective instantiation, generated hardware, or public contracts. For mechanical changes, still state why they do or do not affect effective code.
11. For each changed interface, state compatibility effects for callers and callees: ports added/removed/renamed, bundle field changes, width/parameter changes, ready/valid semantics, AXI channel role or payload changes, and required downstream updates.
12. For each changed algorithm or state machine, compare initial/reset behavior, first transaction behavior, all changed branches/cases, simultaneous-request behavior, priority/tie behavior, and state update effects.
13. For memory/cache/XSCache modules, compare stage-by-stage behavior and identify which stage changed, including set/bank/way/entry index calculation, MSHR/replay/refill/writeback behavior, and empty/full/backpressure logic.
14. End with a migration/risk summary: required code changes, verification focus, likely regressions, and open questions that need waveform, elaboration, or test evidence.

Diff analysis rules:
- Do not output only a patch summary. Convert changed code into microarchitecture analysis using the same evidence, algorithm, control-path, data-path, storage, FSM, and signal-provenance requirements as single-branch analysis.
- For every changed signal or expression, trace producer, consumers, parameter dependence, timing stage, reset/first-use behavior when applicable, and a concrete scenario where the base and target branches differ.
- For every changed table, queue, buffer, array, register group, valid bit, pointer, or replacement state, compare `update`, `release`, `replace`, and `search/read/probe` behavior across both branches, including conflict priority and empty/full/backpressure effects.
- For every changed selector, arbiter, mux priority, grant vector, or ready fanout, compare request qualification, simultaneous-request behavior, priority/fairness rule, losing request behavior, and state update effects.
- For every changed pipeline, Decoupled/Valid, AXI/TL/APB, replay, flush, redirect, exception, interrupt, debug, privilege, cache miss/refill/writeback, or predictor update path, show the base behavior, target behavior, and the exact scenario that changes.

## Answer Contract

For each requested module, produce:

- Module role and boundary: what the module owns and what it delegates.
- Theory context: relevant XiangShanLab superscalar/out-of-order concepts and the exact code structures that implement, specialize, or replace those concepts.
- Predictor paper context: for predictor modules, paper-search-agent MCP results, paper algorithm principle, citation/identifier, and explicit distinction from XiangShan implementation.
- Documentation context: relevant Design Doc/course pages and which claims are theory, design intent, or verified code behavior.
- Effective code path: instantiated modules and live connections that determine actual behavior; mention dead/unused code only as non-effective. Include analyzed source commit and line-numbered Chisel evidence for each effective path.
- Microarchitecture parameters: where relevant parameters are defined, how they enter the module, and how they change port counts, entry counts, widths, algorithms, or optional features.
- Instruction latency and throughput: per instruction or instruction class, report source-proven latency path, best-case and variable contributors, steady-state initiation interval/throughput, bottleneck resource, and uncertainty. Include FU config/wrapper, pipeline stages, issue/select, writeback, commit, memory/cache, replay, and resource-contention evidence as applicable.
- Interaction interface: key inputs, outputs, ports, inter-module connections, handshakes, AXI/TL/APB channels, redirects, flushes, exceptions, interrupts, debug-mode signals, privilege metadata, and performance/debug outputs. Every important port and connection must include Chisel file:line evidence and a short core code snippet.
- Difftest architectural-state coverage: when difftest is relevant, map every emitted difftest signal/event to its producer, timing condition, valid/enable condition, commit or trap association, and downstream reference-model meaning. Cover RISC-V specification-visible int/fp/vector registers, CSR state, exception/trap state, interrupt state, memory virtual/physical address state, cache state, and every queue/buffer state exposed or needed to explain the signal.
- Theory-to-code mapping: map concepts such as structural/data/control hazards, multi-issue, rename, dependency tracking, wakeup/select, bypass, physical registers, ROB, speculation, precise exception, and memory ordering to concrete modules/signals.
- Why it exists: the pipeline, speculation, ordering, bandwidth, latency, or correctness problem it solves.
- Index and address calculation: for every table/array/queue/cache/bank access, explain how the index is calculated, what parameters determine its width/range, which bits select bank/set/way/entry, how pointer arithmetic or wraparound works, and where the index is consumed.
- Memory pipeline stage analysis: for every `mem`, `cache`, or XSCache target, include a stage-by-stage table covering each stage's work, payload/control registers, index/allocation calculation, FSM/valid state, stall/flush/replay behavior, and output.
- Algorithm analysis: selection/replacement/allocation/free-index/arbitration/update rules, priority order, exception/interrupt/debug/privilege priority, AIA interrupt priority/delivery, IOPMP permission matching, AXI address routing/outstanding/burst/response algorithms, predictor lookup/update/recovery principle, pseudocode-level behavior, initialization/reset behavior, first-transaction behavior, all major cases/branches, invalid/empty/full behavior, tie handling, simultaneous-request arbitration behavior, and corner cases. Every algorithm explanation must cite exact Chisel source lines and include the core code snippet from the analyzed commit.
- Algorithm example walkthrough: for each frontend branch predictor or predictor-like component, include a concrete worked example that walks through lookup, provider/target/direction selection, prediction output, update/training, allocation/replacement, and redirect/recovery when applicable. The example must name concrete signal values or representative bit/counter states, map each step to Chisel source lines, and end with the exact downstream effect on `full_pred`, `jalr_target`, `br_taken_mask`, `last_stage_meta`, predictor table state, RAS stack state, FTQ update, or BPU redirect/history state. For non-effective predictors, label the example as non-effective and explain what current effective module replaces it.
- Stage-by-stage predictor algorithm: for each frontend branch predictor or predictor-like component, include a stage table for `s0/s1/s2/s3` and update/redirect stages, with inputs, table or stack access, index/tag/pointer calculation, selection rule, metadata captured, state update, ready/stall condition, output, and exact source lines.
- Redirect signal generation: for frontend analysis, explicitly trace how `s2_redirect`, `s3_redirect`, backend redirect, and predictor-local redirect/cancel/recovery signals are generated, what condition triggers them, how they interact with flush and history/RAS/FTQ repair, and which downstream module consumes them.
- Predictor relationship: for frontend branch prediction analysis, include a code-proven relationship map among `FauFTB`/uFTB, `FTB`, `Tage`, `SC`, `ITTAGE`, `RAS`/`newRAS`, `Bim`/base table, and `BPU`/`Composer`. State the effective chain order, each predictor's responsibility, override/refinement priority, metadata/update/recovery linkage, disagreement handling, and at least one cross-predictor example with exact Chisel line evidence.
- Scenario mapping: include a table for replay, redirect, conflict, contention, and resource empty/full cases. For each case, state trigger condition, involved resources/requesters, code evidence, arbitration or priority rule, loser/blocking behavior, state update, recovery or retry path, and user-visible or downstream effect.
- Predictor algorithm principle: for every predictor, explain the paper-backed principle, lookup path, update/training path, recovery path, storage state, scenario examples, and code mapping.
- Control-signal rationale: for every behavior-changing control signal, explain who produces it, why it exists, what bug/hazard/resource conflict it prevents or enables, and give a concrete scenario where it matters.
- FSM-state rationale: for every explicit FSM state or implicit valid/status state, explain why the state exists, what transaction phase it represents, what would be wrong without it, and give an example scenario that enters or exits it.
- Diagrams: generate a key Mermaid data-path diagram, a Mermaid module-interface diagram, and waveform-draw timing diagrams for handshake/control timing when the analysis involves multiple modules, stages, queues, arrays, or handshakes.
- State-machine analysis: states, why each state exists, example scenarios, transition conditions, outputs by state, entry/exit conditions, and relation to ready/valid backpressure.
- Control path: focus on mux selects, valid/ready/fire, AXI AW/W/B/AR/R channel controls, arbiters, FSM transitions, stalls, redirects, cancels, replays, exceptions, interrupts, wakeup, commit, and pipeline stage control signals; for each key signal, include why it exists and a scenario example.
- Data path: payload movement, pipeline registers, data transforms, muxes, arrays, bypass/forwarding, queue movement, and writeback/refill paths. Every datapath segment must include Chisel source line numbers and a short core code snippet.
- Storage structures: every important queue/table/array/register group, its owner, reset/initial value, full `update` / `release` / `replace` / `search` behavior, and all read/write port conflict behavior. For each operation, include the exact timing, fire/enable condition, calculated index/address/pointer, payload contents, valid-bit set/clear/hold effect, conflict priority, flush/cancel/replay interaction, empty/full/almost-full condition, and backpressure behavior. For port conflicts, cover same-cycle read/write same index, multiple writes same index, multiple reads with limited ports, RAW/WAR/WAW behavior, bypass/forwarding/assert behavior, and which request wins, stalls, retries, or is dropped.
- Signal provenance: for key signals, list `from what` and `to what`, explain why the signal exists, and give a concrete scenario where the signal changes behavior.
- Dynamic flow: describe normal path, speculative path, and at least one exceptional/replay/redirect/miss path when relevant.
- chiselAIA / chiselIOPMP / AXI Bus: when relevant, identify APLIC/IMSIC or IOPMP boundary, AXI master/slave roles, AW/W/B/AR/R channels, protocol control signals, permission/interrupt behavior, backpressure, error responses, and exact source evidence.
- Difftest signals: when relevant, identify difftest module/bundle/event names, enable gating, payload fields, architectural visibility, speculative-versus-committed timing, cache-state meaning, per-queue state meaning, exception/interrupt/memory-address provenance, and exact source evidence.
- Source evidence: include the analyzed source commit, file paths, class/module names, exact line references for algorithms/ports/connections/datapaths, and concise Chisel core code snippets. Line references are mandatory, not optional, for all behavior-changing claims.
- Branch comparison evidence: when comparing two branches, include base and target branch names, exact commit SHAs, selected file set, diff command or method, per-change classification, base and target line references, changed code snippets from both sides, and a current-skill-style code analysis of each semantic diff: who/why/how/from what/to what, affected algorithm/control path/data path/storage/FSM/index/handshake behavior, concrete scenario difference, behavioral impact, compatibility risk, and verification focus.
- Saved Markdown path: when producing a module analysis file, save it under the code-deep-dive course directory and report the absolute path.
- Tutorial output: when the user asks for a tutorial, course-ready document, or Mem-MDP-style chapter layout, keep the canonical numbered chapters, remove generator-only `原章节` wrappers and empty placeholders, and preserve all effective source evidence, design-doc traceability, cross-boundary analysis, diagrams, WaveDrom, scenarios, and verification content. Run `scripts/tutorialize_frontend_docs.py <directory>` after the Markdown has been generated.
- Title numbering: generated tutorial Markdown must keep explicit numeric prefixes at every heading level (`## 1.`, `### 1.1.`, `#### 1.1.1.`). The post-processor should renumber headings after insertions or deletions so the sequence stays monotonic.
- CSR control for Frontend: section 16 must list the real branch-predictor enable control chain from `sbpctl` CSR fields to `CustomCSRCtrlIO.bp_ctrl`, Backend `frontendCsrCtrl`, Frontend `bpu.io.ctrl`, and BPU sub-predictor `io.enable`. Include `ubtbEnable`, `abtbEnable`, `mbtbEnable`, `tageEnable`, `scEnable`, `ittageEnable`, and `rasEnable`; explicitly state that `fallThrough`, `MicroTage`, and `MicroRas` are fixed enabled in the effective BPU code and that Constantin can override CSR bits when enabled.
- Verification special attention: include a `验证特别注意` table with verification ID, risk/invariant, directed stimulus, expected observation, named checker/coverage, and exact effective source evidence.

Use English for the generated analysis unless the user explicitly asks for another language.

## Module Navigation

Use these starting points for Kunminghu v2/v3 style trees:

- Top level: `XSCore.scala`, `XSTile.scala`, `Backend.scala`, `Frontend.scala`, `MemBlock.scala`, `L1Cache.scala`
- Backend: `backend/decode`, `backend/rename`, `backend/dispatch`, `backend/issue`, `backend/exu`, `backend/fu`, `backend/datapath`, `backend/regcache`, `backend/rob`, `backend/ctrlblock`
- Frontend: `frontend/IFU.scala`, `frontend/Frontend.scala`, `frontend/NewFtq.scala`, `frontend/IBuffer.scala`, `frontend/BPU.scala`, `frontend/FTB.scala`, `frontend/Tage.scala`, `frontend/ITTAGE.scala`, `frontend/SC.scala`, `frontend/Bim.scala`, `frontend/RAS.scala`, `frontend/icache`
- Memory/cache: `mem/MemBlock.scala`, `mem/pipeline`, `mem/lsqueue`, `mem/sbuffer`, `mem/mdp`, `mem/prefetch`, `mem/vector`, `cache/L1Cache.scala`, `cache/CacheInstruction.scala`, `cache/dcache`, `cache/mmu`, `cache/wpu`
- XSCache: `coupledL2`, `openLLC`, `xscache/chi`, `xscache/common`, `coupledL2/prefetch`, `coupledL2/utils`, `openLLC/chi`, `openLLC/utils`
- AIA/IOPMP/AXI: `chiselAIA`, `ChiselAIA`, `APLIC`, `IMSIC`, `AXIRegIMSIC`, `chiselIOPMP`, `ChiselIOPMP`, `IOPMP`, `AXI4MasterNode`, `AXI4SlaveNode`, `AXI4Bundle`, `AXI4Xbar`, `AXI4Buffer`, `AXI4ToTL`, `TLToAXI4`, `AXI4Memory`
- Difftest: search for `difftest`, `DiffTest`, `Difftest`, `DifftestModule`, `DifftestArch`, `DifftestCSR`, `DifftestTrap`, `DifftestInterrupt`, `DifftestLoad`, `DifftestStore`, `DifftestL1`, `DifftestCache`, and difftest package imports across backend, ROB/commit, CSR, mem, cache, and top-level files.

## Guardrails

- At the start of analysis, perform the weekly sync check described in `references/weekly-sync.md` for local docs/course inputs; if sync is skipped, dirty, missing, or fetch-only, state that in the analysis scope. XiangShan source code must still be obtained directly from `https://github.com/OpenXiangShan/XiangShan.git` unless the user explicitly supplies a local path.
- When generating module code-analysis Markdown, save it under the code-deep-dive course directory using `references/analysis-output.md`; do not overwrite existing files unless explicitly requested.
- Treat XiangShanLab theory docs as concept definitions, and Design Doc as design intent; neither proves implementation. Verify with effective source code.
- Always connect theory terms to exact code artifacts: module/class, IO bundle, parameter, storage structure, control signal, data path, algorithm, or FSM. Include analyzed commit and exact Chisel line numbers for these artifacts.
- Distinguish `backend` execution pipelines from `mem` pipeline units and `cache/dcache` data arrays/mainpipe.
- Treat `cache/mmu/TLB.scala` and related files as the likely ITLB/DTLB implementation area; frontend may instantiate or connect instruction-side TLB signals through fetch/icache bundles.
- When explaining load/store-class memory instructions, always expand both `mem` modules and `cache` modules on the effective path; when the request reaches XSCache/L2/L3/CHI, also expand XSCache modules. For all memory-related analysis, explicitly describe each pipeline stage, what work it performs, how its FSM/valid state advances, and which index/allocation algorithm it uses.
- When explaining instruction timing, distinguish latency from throughput. Latency is the cycles from the chosen start event to the chosen end event; throughput is the steady-state accept/issue/complete rate or initiation interval. Always name the start/end events, best-case assumptions, variable contributors, and bottleneck resource.
- When explaining CBO or fence behavior, search both decode/FU files and cache/memory files; the behavior may be split across decode classification, FU control, memory ordering, and cache request handling.
- For branch prediction, use `references/predictor-papers.md` and `paper-search-agent-mcp` to search relevant papers before explaining algorithm principles. Separate paper algorithm, design intent, and effective XiangShan code. Separate predictor storage lookup from prediction response generation, update/allocation, redirect recovery, and commit training.
- For every frontend branch predictor, do not stop at a general algorithm description. Include at least one concrete algorithm example walkthrough with representative PC/history/table/counter/RAS/metadata values, and show how those values flow through the code-proven lookup, selection, update/allocation, and recovery rules. The example may use simplified representative values, but must keep bit slicing, table selection, counter direction, and priority rules faithful to the cited code.
- For frontend branch prediction, always separate per-stage algorithm behavior from redirect generation. Do not collapse a predictor into one lookup/update paragraph: enumerate what happens in every effective stage and then separately trace how redirect, override, cancel, reopen, and recovery signals are generated or influenced by that predictor.
- For frontend branch prediction, always explain relationships between predictors as a separate concern from each predictor's local algorithm. Identify which component gives the fast early guess, which component refines direction, which component supplies direct/indirect/return target, which component composes the final prediction, and how metadata, FTQ update, redirect, and history/RAS recovery keep the components coherent when they disagree.
- For every `who` answer, include the parameter owner when parameters determine the updater count, width, entries, or optional behavior.
- Whenever code computes an index, address, pointer, bank selector, set selector, way selector, queue entry selector, allocation slot, free-list slot, MSHR slot, replay entry, PTW entry, victim way, `OHToUInt`, `UIntToOH`, `PriorityMux` index, `PopCount` rank, `wrap`, `head`, `tail`, or `ptr`, explain the full calculation, allocation/free policy, and the consumer. Do not only name the signal.
- Whenever code implements an algorithm, explain the algorithm.s operating principle, initialization/reset state, first valid/request behavior, all major cases, priority/tie behavior, simultaneous-request arbitration behavior, index/allocation choice, why the control decisions exist, example scenarios for important decisions, and how state changes for each case. Cite exact Chisel source lines and show the short core code snippet from the analyzed commit.
- Whenever code can replay, redirect, conflict, contend for a resource, or block because a resource is empty/full/almost-full, map the concrete scenario from trigger to effect. Do not only say "it stalls" or "it replays"; identify the exact resource, requesters, priority, blocked path, held or cleared state, retry/redirect target, and downstream observer.
- For every `valid`, `ready-valid` payload valid, table valid bit, queue entry valid bit, FSM-valid state, or status-valid bit, explicitly document when it is set, when it is cleared, when it holds, why it exists, one realistic scenario where it matters, what flush/cancel/replay redirects affect it, and which downstream logic observes it.
- For every storage structure, organize behavior around `update`, `release`, `replace`, and `search/read/probe` even if the code names them enqueue/dequeue/read/write/allocate/free/lookup/match. For each operation, state when it happens, which index is used and how that index is calculated, what content is updated/released/replaced/searched, how valid/status bits change, and which operation wins if update/release/replace/search collide in the same cycle. Also analyze read/write port conflicts: same-cycle read and write to the same index, two writes to the same index, more requesters than physical ports, bypass/forwarding/assert behavior, and whether the losing request stalls, retries, replays, is masked, or is illegal.
- For every arbiter, selector, mux-priority network, grant vector, ready fanout, or request scheduler, enumerate all requesters and analyze what happens when different requesters arrive simultaneously. Explain why each key grant/ready/select signal exists and give a conflict scenario that demonstrates its role. State request qualification, priority or fairness rule, grant encoding, data selected, ready/backpressure returned to each requester, losing request behavior, and state updates caused by the grant.
- For every nontrivial module, include Mermaid diagrams and waveform-draw handshake timing diagrams unless the user asks for prose only. Use `flowchart LR` for data/interface paths, `stateDiagram-v2` for explicit FSMs when useful, and fenced `waveform-draw` blocks with WaveDrom-compatible signal JSON for timing diagrams.
- For top-level/full-chain output, include both `Top-Level Module Connectivity` and `Frontend/Backend Pipeline Stages` Mermaid sections. Keep each module pair at no more than three bundled connections; split crowded connectivity into multiple Mermaid subgraphs rather than adding dense cross-lines.
- Make every generated `waveform-draw` block directly previewable in VS Code: emit strict WaveDrom-compatible JSON, keep `clk` first, use real signal names, and rely on the configured `bmpenuelas.markdown-preview-wavedrom` extension with `markdown-preview-wavedrom.LanguageIdentifier` set to `waveform-draw`. Tell the user to open the Markdown Preview rather than expecting the source editor to draw the waveform inline.
- For exception, interrupt, debug, and privilege behavior, identify the exact priority and propagation path; do not collapse them into a generic flush explanation. For chiselAIA, expand APLIC/IMSIC delivery, CSR interaction, interrupt priority, privilege/virtualization legality, and MSI/MMIO access paths. For chiselIOPMP, expand protected masters/slaves, permission match algorithm, deny/error response, config path, and bypass behavior. For AXI, expand master/slave roles, AW/W/B/AR/R channels, valid/ready fire, payload stability, `last`, `resp`, `id`, burst, outstanding tracking, and backpressure.
- For difftest behavior, read `references/difftest.md` and separate architectural state from microarchitectural debug state. Do not treat speculative queue/cache/internal state as RISC-V architectural state unless the code shows it is commit-visible or reference-model-visible.
- For every queue or buffer, explicitly explain empty/full checks and what upstream/downstream logic observes them.
- For every generated document, read `references/verification-special-attention.md` and include a `验证特别注意` section.
- Never present Design Doc intent as effective implementation without a line-by-line source mapping; include `Design Doc baseline`, `XiangShan source baseline`, a traceability matrix, and explicit discrepancy statuses. Tie every row to effective code evidence, exact stimulus, expected observation, and a named checker; cover boundaries, conflicts, recovery, forward progress, and context/exception isolation whenever reachable.
- For every generated document that can observe an address or instruction stream, include a `跨边界代码解析` section. Analyze at least one concrete case for each reachable boundary: virtual-page crossing, cache-line crossing, and MMIO/uncache crossing. Split the request into sub-requests, identify translation and permission checks for each piece, describe line/set/beat/MSHR/uncache-entry allocation and response merge, state whether speculation is allowed, and trace exception, redirect, flush, retry, commit, and forward-progress behavior. Never describe a cross-boundary access as a single atomic request unless the effective code proves that it is atomic.
- In Dynamic Operation, always include speculative path when the module participates in prediction, out-of-order execution, replayable memory operations, cache prefetch, coherence speculation, or permission checks before commit.
- Avoid generic CPU textbook summaries unless they are tied to a concrete XiangShan/XSCache signal, queue, table, state machine, algorithm, port, connection, datapath segment, or module with exact Chisel line evidence.
- Do not leave raw intermediate-generation labels such as `原章节:...`, `本节保存...`, or `本模块原文没有单独的本节标题` in tutorial-facing output.