A method and system for embedded microkernel iterative generation and graph rewriting based on physical constraint feedback

By introducing a physical constraint feedback closed-loop mechanism and using a large language model to iteratively correct the abstract task graph, the problems of resource exhaustion and multi-objective trade-offs in embedded code generation are solved, enabling autonomous diagnosis and repair, and improving the pass rate of generated code and system robustness.

CN122173069APending Publication Date: 2026-06-09ZHEJIANG UNIV
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
ZHEJIANG UNIV
Filing Date
2026-04-24
Publication Date
2026-06-09

Smart Images

  • Figure CN122173069A_ABST
    Figure CN122173069A_ABST
Patent Text Reader

Abstract

This invention discloses an embedded microkernel iterative generation and graph rewriting method and system based on physical constraint feedback. The method establishes a reverse feedback loop from a deterministic backend to the LLM (Limited Language Management Module): First, the deterministic backend is used as a "physical verifier" to tentatively synthesize the initial task graph; when physical violations such as register overflow or volume exceeding limits are detected, a physical diagnostic report containing bottleneck node information is generated; then, the diagnostic report is converted into natural language prompts using feedback encoding technology; finally, the LLM is driven to execute graph rewriting strategies such as node splitting and input serialization to correct the task graph topology. This invention achieves a closed-loop iteration of "physical problem, semantic solution." Experiments show that this method can increase the generation success rate of complex embedded tasks on extremely constrained hardware from 32% to 94%, significantly enhancing the robustness and adaptability of the system.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the fields of intelligent software engineering and embedded system compilation technology, specifically to an embedded microkernel iterative generation and graph rewriting method and system based on physical constraint feedback. This invention utilizes the feedback of physical layer analysis results to drive the Large Language Model (LLM) to iteratively rewrite and correct the Abstract Task Graph (ATG) to meet stringent hardware resource constraints. Background Technology

[0002] In the emerging technology path of generating embedded code using Large Language Models (LLMs), existing solutions typically adopt a "one-pass pipeline" model: first, the LLM parses the user intent into an intermediate representation (such as a task graph), and then a deterministic backend maps it into machine code.

[0003] However, the inventors discovered in practical applications that this unidirectional generation mode has significant limitations when faced with extremely limited physical resource constraints, mainly in the following two aspects: 1. Resource Exhaustion caused by the "semantic-physical" gap LLMs only possess logical-level reasoning capabilities and cannot perceive the physical limitations of the target hardware (such as having only 16 general-purpose registers). When an LLM generates a complex task graph containing a large number of parallel data streams, even if the logic is correct, it may cause severe "spills" in the backend during register allocation, or even fail to allocate registers due to insufficient capacity. Existing deterministic backends can perform local optimizations (such as zero-copy), but they cannot change the topology of the task graph itself. Once the physical hardware boundary is reached, the system can only terminate with an error.

[0004] 2. Static optimization cannot satisfy multi-objective trade-offs (Pareto trade-offs). The optimization goals of embedded systems are often contradictory; for example, pursuing extreme speed may sacrifice code size. One-way generation mode typically produces only one fixed solution. If the generated kernel functions correctly but its size exceeds the remaining Flash space, or the timing of the critical path does not meet real-time requirements, the existing static backend cannot automatically adjust the upper-level logic structure to adapt to these dynamic constraints.

[0005] Traditional compilers (such as GCC) include multi-pass optimization, but their rewriting rules are fixed and cannot rethink the implementation of tasks at the "algorithm level" like LLM can, for example, rewriting a parallel large matrix multiplication as a serial block computation to save registers.

[0006] Therefore, there is an urgent need for a closed-loop mechanism that can establish feedback from the "physical world" to the "semantic world," enabling LLM to proactively rewrite the task graph based on the physical analysis results from the backend, thereby achieving adaptive satisfaction of physical constraints. Summary of the Invention

[0007] The purpose of this invention is to address the shortcomings of existing technologies by providing an embedded microkernel iterative generation and graph rewriting method based on physical constraint feedback. Building upon the "semantic parsing-deterministic synthesis" approach, this invention adds a reverse feedback loop, utilizing a deterministic backend as a "physical verifier" to guide the LLM in iteratively refining the abstract task graph.

[0008] The objective of this invention is achieved through the following technical solution: Firstly, this invention provides an embedded microkernel iterative generation and graph rewriting method based on physical constraint feedback, the method comprising the following steps: S1: Initial exploratory synthesis: Receive the initial abstract task graph (ATG) generated by the large language model (LLM) based on user intent, input the ATG into the deterministic backend for exploratory synthesis without generating a final binary file, and record the physical resource consumption index. S2: Physical constraint verification and feedback: The physical resource consumption index is compared with the preset target hardware physical threshold; if it is determined that the physical constraint is violated, the task node that caused the violation is located and a physical diagnostic report containing the violation type and bottleneck data is generated. S3: Semantic feedback encoding: Convert the physical diagnostic report into feedback prompts in natural language format, wherein the feedback prompts contain specific correction instructions for the bottleneck node; S4: Semantic Graph Rewriting: Input the feedback prompts into the LLM, drive the LLM to rewrite and transform the topology of the ATG while keeping the original task function semantics unchanged, and generate the corrected ATG. S5: Iterative convergence: Based on the corrected ATG, re-execute step S1, and repeat the above steps until the physical resource consumption index meets the physical threshold or reaches the preset maximum number of iterations.

[0009] Furthermore, the physical resource consumption indicators include at least one of the following: Global register pressure: The number of peak active variables obtained by performing a global activity analysis on the ATG during exploratory synthesis by a deterministic backend; Code segment size: An estimated total number of bytes in the target machine code or target instruction sequence concatenated from atomic primitives; Critical path timing: An estimate of the cumulative clock cycles of the longest path obtained from critical path analysis; The physical resource consumption index is used to compare with a preset target hardware physical threshold to determine whether physical constraints are violated.

[0010] Furthermore, the graph rewriting includes at least one of the following strategies and is triggered by the violation type or recommended rewriting strategy identifier in the physical diagnostic report: Node splitting: Split the bottleneck task node into two or more serially connected sub-task nodes to reduce the number of instantaneous inputs or the number of peak active variables; Input serialization: Insert dependency edges between originally parallel task branches to make them execute serially, thereby reducing the overlap of active regions; Recalculation: Remove long-lived intermediate variables and insert a task node to recalculate the variable before the point of use, in exchange for lower register usage; Primitive replacement: Replace functionally equivalent but resource-intensive atomic primitives without changing the semantics of the input / output interfaces, in order to meet code size or timing thresholds.

[0011] Furthermore, the semantic feedback encoding employs a template-based slot-filling method, including: Pre-build a library of prompt word templates corresponding to different violation types; Extract and populate at least one set of the following slot fields from the physical diagnostic report: bottleneck task node identifier, violation type, current indicator value, corresponding threshold, set of allowed graph rewrite operations, and constraint statements that keep the semantics of the task input and output interfaces unchanged; The output provides feedback prompts to drive the LLM to perform the constrained rewriting of the local subgraph.

[0012] Furthermore, the method also includes a Pareto maintenance step for multi-objective optimization: in step S4, the LLM is instructed to generate multiple variant ATGs with different rewrite strategies, and steps S1 to S2 are executed respectively to obtain the corresponding physical resource consumption index vectors, and a non-dominated solution set is maintained; the physical resource consumption index vectors include at least two of the following: register pressure, code segment volume, and critical path timing, so as to allow for selection between performance and resource consumption.

[0013] Secondly, the present invention also provides an embedded microkernel iterative generation and graph rewriting system based on physical constraint feedback, the system comprising: A deterministic backend tentative synthesizer is used to perform tentative synthesis on an input ATG without generating a final binary file and output physical resource consumption metrics, wherein the physical resource consumption metrics include at least one of register pressure, code segment volume, or critical path timing. The physical monitoring and bottleneck location module is used to compare the physical resource consumption index with a preset threshold, and locate the bottleneck task node set based on the trial-and-error synthesis intermediate results when a violation is detected. A diagnostic report generator is used to generate a structured physical diagnostic report, which includes at least the violation type, current value, threshold, bottleneck task node identifier, and suggested rewrite strategy identifier. The feedback encoder, which has a prompt word template library and slot filling rules, is used to convert the structured physical diagnostic report into natural language feedback prompt words. The feedback prompt words contain a set of allowed graph rewriting operations and constraint statements that keep the semantics of the input and output interfaces unchanged. The semantic rewriting engine, which integrates a large language model, is used to perform constrained graph rewriting transformations on the local subgraphs corresponding to bottleneck task nodes based on the feedback prompts to generate the corrected ATG. The iteration controller manages the iteration process and sets the maximum number of iterations. It detects oscillations and triggers a rollback or switches the rewrite strategy when the maximum number of iterations is reached or an oscillation is detected.

[0014] Thirdly, the present invention also provides an electronic device, including a memory and a processor, wherein the memory stores a computer program, and the processor executes the program to implement the aforementioned embedded microkernel iterative generation and graph rewriting method based on physical constraint feedback.

[0015] Fourthly, the present invention also provides a computer-readable storage medium having a computer program stored thereon, wherein the program, when executed by a processor, implements the aforementioned method for iterative generation and graph rewriting of an embedded microkernel based on physical constraint feedback.

[0016] Fifthly, the present invention also provides a computer program product, including a computer program, which, when executed by a processor, implements the aforementioned method for iterative generation and graph rewriting of an embedded microkernel based on physical constraint feedback.

[0017] The beneficial effects of this invention are: 1. Algorithm-level optimization capability: Unlike traditional compilers that can only make instruction-level adjustments, this invention utilizes the semantic understanding capability of LLM to perform algorithm-level structural reorganization (such as changing the order of computation and splitting tasks), achieving higher-dimensional optimization.

[0018] 2. Self-Healing: When the generated code has potential timing violations or resource conflicts, the system can automatically diagnose and "heal" the task graph without manual intervention, which significantly improves the robustness of automated generation tools.

[0019] This invention realizes a closed-loop iteration of "physical problem, semantic solution". Experiments show that this method can increase the generation pass rate of complex embedded tasks on extremely constrained hardware from 32% to 94%, significantly enhancing the robustness and adaptability of the system. Attached Figure Description

[0020] To more clearly illustrate the technical solutions in the embodiments of the present invention or the prior art, the drawings used in the description of the embodiments or the prior art will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0021] Figure 1 This is a flowchart of the closed-loop iterative generation method based on physical constraint feedback provided in this embodiment of the invention. Figure 2 This is a logical schematic diagram of the physical diagnostic report generation and feedback encoding in an embodiment of the present invention; Figure 3 This is a schematic diagram of the LLM execution graph rewriting strategy (node ​​splitting and serialization) in an embodiment of the present invention; Figure 4 This is a schematic diagram of the iterative convergence curve under resource constraints in an embodiment of the present invention. Detailed Implementation

[0022] To make the objectives, technical solutions, and advantages of this invention clearer, the invention will be further described below with reference to the accompanying drawings and examples. It should be understood that the specific examples described herein are merely illustrative and not intended to limit the invention.

[0023] like Figure 1 As shown, the present invention provides an embedded microkernel iterative generation and graph rewriting method based on physical constraint feedback, comprising the following steps: S1: Initial mission map generation and physics exploration.

[0024] The system receives user intent and uses LLM to generate an initial version of the Abstract Task Graph (ATG-v0). This ATG is then input into a deterministic backend for a "Dry Run." During this process, the backend does not generate a final binary file but instead records physical resource usage (such as peak register pressure, estimated code segment size, and theoretical instruction cycles). The Dry Run performs at least instruction selection / atomic primitive concatenation and resource estimation, and outputs physical resource consumption metrics.

[0025] S2: Physical constraint verification and feedback encoding.

[0026] The physical metrics obtained through trial synthesis are compared with preset hardware constraint thresholds (such as the maximum number of available registers and the maximum code size).

[0027] If the constraints are met, the final code will be output.

[0028] If a constraint is violated (e.g., register overflow), the backend locates the specific task node (Node ID) causing the violation based on the intermediate results of the Dry Run and generates a structured "Physical Diagnostic Report." This report is encoded as LLM-understandable natural language prompts, such as: Output of node T5 The inflow of data caused register pressure to reach 18, exceeding the hardware limit of 16. ".

[0029] S3: Feedback-based Semantic Graph Rewriting.

[0030] Based on a pre-built prompt word template library and slot filling rules, the physical diagnostic report is converted into feedback prompt words in natural language format. The feedback prompt words include at least: bottleneck task node identifier, violation type, current value and threshold, set of allowed graph rewriting operations, and constraint statements that maintain the semantics of the task input and output interfaces. The location of the bottleneck task node set includes at least one of the following: the set of active variables corresponding to the peak register pressure time obtained from global activity analysis and mapped to ATG nodes; the over-threshold path obtained from critical path analysis and mapped to ATG nodes; or the code segment volume contribution obtained by accumulating the number of atomic primitive instruction bytes of each node and mapped to ATG nodes. The physical diagnostic report is fed back to the LLM, triggering a graph rewriting instruction. Based on the feedback information, the LLM performs a graph rewriting transformation on the topology of the ATG (the local subgraph corresponding to the bottleneck task node), while maintaining the original task input / output interface semantics and data dependency semantics, to generate the corrected ATG. Transformation strategies include, but are not limited to: Node Splitting: Decompose a complex atomic task into two sequential subtasks to reduce transient register requirements; Re-materialization: Insert instructions to re-materialize nodes in place of long-distance register holding; Serialization: Forces parallel branches to be executed serially, trading time for space.

[0031] S4: Iterative convergence and multi-objective optimization.

[0032] The corrected ATG (ATG-v1) is re-entered into step S1 for a new round of physics exploration. This process is repeated until the physics resource consumption index meets the stated physics threshold or the maximum number of iterations is reached. For multi-objective optimizations (such as velocity and volume), the system maintains a set of Pareto Frontiers, reserving the optimal solutions from different iteration versions for the user to choose from.

[0033] Example 1: Physical Constraint Verification and Feedback Coding Method This embodiment describes in detail how a deterministic backend detects resource bottlenecks during the "Dry Run" phase and transforms underlying physical error information into semantic feedback prompts that LLM can understand.

[0034] 1. Physical exploration and constraint verification The deterministic backend Dry Run is a backend process that performs exploratory synthesis and resource estimation on the Task Graph (ATG). It is used to complete instruction selection / atomic primitive concatenation, register allocation attempts, code volume estimation, and critical path estimation without outputting a final binary file, and output physical metrics that can be used for constraint verification. This embodiment introduces a "Physical Monitor" in the deterministic synthesis process.

[0035] Input: Initial version of the Abstract Task Graph (ATG-v0). The Abstract Task Graph (ATG) is a directed graph structure used to describe the task execution logic. Nodes represent atomic tasks or atomic primitive calls, and edges represent data dependencies or control dependencies. An ATG must contain at least node identifiers, input / output data interfaces, and dependencies.

[0036] Monitoring indicators: Register Pressure: The maximum number of active registers at any given time, as determined by global activity analysis. .

[0037] Code Size: The total number of bytes of instructions for all primitives.

[0038] Critical Path Timing: The cumulative number of instruction cycles on the longest path.

[0039] Verification logic: Set the physical threshold for the target hardware (e.g.: = 16, = 4096 Bytes).

[0040] in, This is a violation determination flag, indicating whether the current tentative synthesis result violates physical constraints. It is generally a Boolean value, with true indicating a violation and false indicating no violation. It refers to the number of active variables, or the peak number of active variables; This refers to the maximum number of available registers, indicating the upper limit of register resources that the target hardware can provide, such as 16 general-purpose registers. > When this occurs, it indicates that the implementation corresponding to the current task graph requires more registers than the hardware can handle, which will lead to register overflow or allocation failure; Size is the code size; This is the maximum allowed code size, when Size > If this happens, it means the generated code cannot be placed into the target device.

[0041] like If true, the system pauses generation and triggers the diagnostic process.

[0042] 2. Physical diagnostic report generation A physical diagnostic report is structured data output by the deterministic backend when it detects a violation of a physical metric threshold. It includes at least the violation type, bottleneck node identifier, current value, threshold, and suggested rewrite policy identifier. For example... Figure 2 As shown, this illustrates how a deterministic backend acts as a "physical verifier," translating underlying register overflows or timing violations into natural language prompts that the LLM can understand. The physical monitor locates the specific task node causing the violation (e.g., at node...). place, Reaching a peak of 18), and generating structured JSON diagnostic data: { "status": "FAIL", "violation_type": "REGISTER_SPILL", "bottleneck_node": "T5", "current_value": 18, "limit_value": 16, "suggestion": "REDUCE_PARALLELISM" } 3. Feedback Encoding To drive the LLM to make corrections, the system must "translate" the structured JSON diagnostic data into natural language instructions that the LLM can understand. This embodiment uses a template-based slot filling method for the conversion: Step A: Build a template library The system has pre-set prompt word templates for different types of physical violations.

[0043] Template 1 (for register overflow): Error: Node {NodeID} causes high register pressure ({Current} >{Limit}). Root Cause: High interaction density in local subgraph. Action: Apply graph rewriting strategies (eg, Node Splitting) to reduce simultaneous liveness. Template 2 (for exceeding volume limits): Error: Total code size ({Current} bytes) exceeds flash limit({Limit}). Action: Replace large primitives with compact alternatives. Step B: Generate the final prompt word. Combining the data from the physical diagnostic report (such as NodeID="T5", Current=18, Limit=16), the data is populated into the template to generate the final physical layer instructions fed back to the LLM: [SYSTEM FEEDBACK] Detection: Physical constraint violation at Node T5. Reason: Register pressure (18) exceeds hardware limit (16). Instruction: Rewrite the graph structure around Node T5 to reduce active variables. Constraint: You may split the node or serialize its inputs, but DONOT change the functional semantics. Example 2: Feedback-based Semantic Graph Rewriting Strategy This embodiment details how the LLM, upon receiving instructions from the physical layer, utilizes its semantic understanding capabilities to perform equivalent transformations on the Abstract Task Graph (ATG). This "algorithm-level refactoring" is something traditional compilers cannot achieve.

[0044] 1. Graph rewriting process Graph rewriting transforms the topology of local subgraphs of an ATG while maintaining semantic equivalence between the task input / output interfaces and data dependencies. The LLM receives an input sequence containing the original abstract task graph (ATG-v0) and a physics feedback prompt, and outputs a corrected task graph ATG (ATG-v1). Based on the physics feedback, the LLM analyzes the bottleneck causes and selects a rewriting strategy from the allowed set of rewriting operations, such as node splitting, input serialization, recomputation, or primitive replacement.

[0045] 2. Core Rewriting Strategies like Figure 3As shown, when the backend diagnostic report indicates "register pressure exceeds threshold," the LLM, guided by constraint prompts, performs an equivalent rewrite of the local subgraph corresponding to the bottleneck node: reducing the instantaneous input quantity through node splitting, and further reducing active region overlap through input serialization, thereby reducing register demand below the threshold. For different physical bottlenecks, the system pre-configures the following graph rewriting modes for the LLM to use: Strategy A: Node Splitting – Addressing Register Overflow Scenario: A single large task (such as large matrix multiplication) At the same time, a large amount of data needs to be loaded, resulting in insufficient input registers. Here, A, B, and C refer to general matrices.

[0046] Transformation: Transforming large tasks Decompose into sequential subtasks and .

[0047] Original logic: After rewriting: ; Effect: Trading time for space. Although the number of instructions increases, the instantaneous register requirement is halved, satisfying hardware constraints.

[0048] Strategy B: Input Serialization – Addressing Register Overflow Scenario: Multiple independent tasks are executed in parallel, causing their outputs to be active simultaneously (Liveness Overlap).

[0049] Transformation: Force the insertion of dependency edges between parallel branches, making them execute sequentially.

[0050] Effect: It shortens the active range of variables, allowing physical registers to be reused.

[0051] Strategy C: Re-materialization – Addressing Register Overflow Scenario: A certain variable It was not used for a long time after it was created, and occupied the register during that time.

[0052] Transformation: Deleting a variable The retention, when needed Insert recalculation in the place The instructions.

[0053] Effect: Trading computation for space. Freeing up long-lived registers.

[0054] Strategy D: Primitive Swapping – Addressing Volume Excess Scenario: High-performance but bulky primitives (such as Unrolled_MemCpy) are used.

[0055] Transformation: Replace it with a primitive that has the same functionality but a smaller size (such as Loop_MemCpy).

[0056] Effect: Trading time for size. The code segment size has been reduced, making it more suitable for smaller Flash files.

[0057] Through the above strategies, LLM can flexibly adjust the topology of ATG without changing the user's intent (functional semantics), thereby "escaping" from the dead end of physical resources.

[0058] Example 3: A Multi-Objective Iterative Optimization Method Based on Pareto Front This embodiment details how the system finds a balance between the often conflicting optimization objectives of "performance" and "code size." During graph rewriting, a single modification can have side effects; for example, while node splitting reduces register pressure, it often increases the number of instructions. Therefore, this invention introduces a multi-objective Pareto optimization mechanism.

[0059] 1. Diversity Generation When the physical monitor triggers feedback, the LLM is instructed to be generated. Instead of a single solution, there are different rewrite variants.

[0060] Variant A (speed-oriented): Prefers to use "Loop Unrolling" or parallelization strategies. Loop Unrolling expands a loop that originally needed to be executed repeatedly into multiple consecutive computational steps directly in the code or task graph, reducing loop control overhead.

[0061] Variant B (Prioritizing Size): Prefers to use "subroutine reuse" or "input serialization" strategies. Among them: node splitting breaks a large node into multiple smaller serial sub-nodes to reduce transient register requirements; subroutine reuse is more like extracting multiple recurring computational segments and sharing the same implementation to reduce code duplication and size.

[0062] 2. Pareto Frontier Maintenance The system maintains a solution set. This contains all valid solutions that are "non-dominated".

[0063] Non-dominated definition: a solution It is non-dominated if and only if there is no other solution. , making Superior to or equal to in all metrics And it is strictly better than in at least one metric. .

[0064] Update process: For each variant of the LLM output The backend calculates its metrics. .

[0065] like If a hard physical constraint is violated (such as a register overflow), it is discarded directly.

[0066] like Satisfy the constraints, and combine them with The existing solutions are compared.

[0067] like If a solution dominates some of the old solutions in the set, then delete the old solutions and add the new ones. .

[0068] 3. User decision support After the iteration is complete, the system will display to the user. The options are listed below. For example: Option 1: Size 1024 Bytes, Time 500 us (suitable for Flash-limited scenarios).

[0069] Option 2: Size 2048 Bytes, Time 200 us (suitable for high-performance scenarios).

[0070] Technical benefits: The system not only "runs" but also provides optimal adaptation code based on the hardware characteristics of specific products (whether cost or performance is the primary concern).

[0071] Example 4: Iterative Convergence Mechanism and Experimental Results Verification This embodiment describes the convergence conditions of the system and, in conjunction with actual test data, verifies the significant advantages of "physical feedback closed loop" over "open loop generation".

[0072] 1. Iterative control logic To prevent LLM from getting stuck in an oscillation during graph rewriting, this invention establishes a strict convergence control mechanism: Maximum Iterations: Sets a threshold (For example, 5 times). If the physical constraints are not met after exceeding the number of attempts, the system will fall back to the "safest and most conservative version" (i.e., the fully serialized version).

[0073] Oscillation Detection: Records the ATG hash value for each iteration. If an oscillation is detected... This indicates an oscillation has occurred, forcibly switching the rewrite strategy, for example, from "node splitting" to "primitive replacement". This indicates a judgment on whether they are equal.

[0074] 2. Example of iterative convergence process like Figure 4 As shown, taking "register pressure" as an example, this demonstrates the convergence process of a typical "large matrix computation" task under the constraint of 16 registers, where the system undergoes multiple iterations (v0 -> v1 -> v2) to ultimately reduce physical resource consumption below the hardware threshold. v0 (Initial Version): LLM generates fully parallel structures.

[0075] Status: Register requirement 22 > 16. (Critical overflow, FAIL) Feedback: "Node T1 causes spill." v1 (first rewrite): LLM performs "node splitting".

[0076] Status: Register requirement 18 > 16. (Slight overflow, FAIL) Feedback: "Still spilling at Sub-node T1a." v2 (second rewrite): LLM performs "input serialization".

[0077] Status: Register requirement 15 < 16. (Constraint satisfied, PASS) Result: Output the final code.

[0078] 3. Comparison of Experimental Data The inventors conducted generation tests of 100 complex embedded tasks on a resource-constrained RISC-V core (configured with only 16 general-purpose registers and 4KB Flash): Test Scope Description: A deterministic backend Dry Run is considered passed if it can complete synthesis and be deemed to "satisfy constraints" under a given threshold (e.g., MaxRegs=16, code segment size not exceeding 4KB target budget). The maximum number of iterations and the rollback strategy for each task adopt the same settings as in Example 4 (e.g., a maximum of 5 iterations, with rollback to a conservative version if the limit is exceeded). The task set may include various computational and data-dependent structures such as sensing acquisition, filtering / matrix calculation, and control loops to cover typical embedded workloads.

[0079] Baseline group: generated only once using LLM (open-loop), without physical feedback.

[0080] Pass rate: only 32%. Most complex tasks fail to compile due to register allocation failures.

[0081] Ours: Enabling Physics Feedback and Graph Rewriting Iteration.

[0082] Pass rate: increased to 94%.

[0083] Average number of iterations: 2.3.

[0084] Self-healing capability: Even if the initial version is completely unusable, the system can automatically repair structural defects and generate runnable code through an average of about 2 "diagnosis-rewrite" cycles.

[0085] 4. Conclusion Experiments have shown that by introducing a physical constraint feedback loop, this invention successfully solves the problem of "difficulty in implementation" of LLM-generated code, and greatly expands the applicability of large model-based code generation technology on low-end embedded devices.

[0086] The above embodiments are used to explain and illustrate the present invention, but not to limit the present invention. Any modifications and changes made to the present invention within the spirit and scope of the claims shall fall within the protection scope of the present invention.

Claims

1. A method for iterative generation and graph rewriting of embedded microkernels based on physical constraint feedback, characterized in that, The method includes the following steps: S1: Initial exploratory synthesis: Receive the initial abstract task graph (ATG) generated by the large language model (LLM) based on user intent, input the ATG into the deterministic backend for exploratory synthesis without generating a final binary file, and record the physical resource consumption index. S2: Physical constraint verification and feedback: The physical resource consumption index is compared with the preset target hardware physical threshold; if it is determined that the physical constraint is violated, the task node that caused the violation is located and a physical diagnostic report containing the violation type and bottleneck data is generated. S3: Semantic feedback encoding: Convert the physical diagnostic report into feedback prompts in natural language format, wherein the feedback prompts contain specific correction instructions for the bottleneck node; S4: Semantic Graph Rewriting: Input the feedback prompts into the LLM, drive the LLM to rewrite and transform the topology of the ATG while keeping the original task function semantics unchanged, and generate the corrected ATG. S5: Iterative convergence: Based on the corrected ATG, re-execute step S1, and repeat the above steps until the physical resource consumption index meets the physical threshold or reaches the preset maximum number of iterations.

2. The method according to claim 1, characterized in that, The physical resource consumption indicators include at least one of the following: Global register pressure: The number of peak active variables obtained by performing a global activity analysis on the ATG during exploratory synthesis by a deterministic backend; Code segment size: An estimated total number of bytes in the target machine code or target instruction sequence concatenated from atomic primitives; Critical path timing: An estimate of the cumulative clock cycles of the longest path obtained from critical path analysis; The physical resource consumption index is used to compare with a preset target hardware physical threshold to determine whether physical constraints are violated.

3. The method according to claim 1, characterized in that, The graph rewriting includes at least one of the following strategies and is triggered by the violation type or recommended rewriting strategy identifier in the physical diagnostic report: Node splitting: Split the bottleneck task node into two or more serially connected sub-task nodes to reduce the number of instantaneous inputs or the number of peak active variables; Input serialization: Insert dependency edges between originally parallel task branches to make them execute serially, thereby reducing the overlap of active regions; Recalculation: Remove long-lived intermediate variables and insert a task node to recalculate the variable before the point of use, in exchange for lower register usage; Primitive replacement: Replace functionally equivalent but resource-intensive atomic primitives without changing the semantics of the input / output interfaces, in order to meet code size or timing thresholds.

4. The method according to claim 1, characterized in that, The semantic feedback encoding employs a template-based slot-filling method, including: Pre-build a library of prompt word templates corresponding to different violation types; Extract and populate at least one set of the following slot fields from the physical diagnostic report: bottleneck task node identifier, violation type, current indicator value, corresponding threshold, set of allowed graph rewrite operations, and constraint statements that keep the semantics of the task input and output interfaces unchanged; The output provides feedback prompts to drive the LLM to perform the constrained rewriting of the local subgraph.

5. The method according to claim 1, characterized in that, The method also includes a Pareto maintenance step for multi-objective optimization: in step S4, the LLM is instructed to generate multiple variant ATGs with different rewrite strategies, and steps S1 to S2 are executed respectively to obtain the corresponding physical resource consumption index vectors, and the non-dominated solution set is maintained; the physical resource consumption index vectors include at least two of the following: register pressure, code segment volume and critical path timing, so as to allow for selection between performance and resource consumption.

6. An embedded microkernel iterative generation and graph rewriting system based on physical constraint feedback, characterized in that, The system includes: A deterministic backend tentative synthesizer is used to perform tentative synthesis on an input ATG without generating a final binary file and output physical resource consumption metrics, wherein the physical resource consumption metrics include at least one of register pressure, code segment volume, or critical path timing. The physical monitoring and bottleneck location module is used to compare the physical resource consumption index with a preset threshold, and locate the bottleneck task node set based on the trial-and-error synthesis intermediate results when a violation is detected. A diagnostic report generator is used to generate a structured physical diagnostic report, which includes at least the violation type, current value, threshold, bottleneck task node identifier, and suggested rewrite strategy identifier. The feedback encoder, which has a prompt word template library and slot filling rules, is used to convert the structured physical diagnostic report into natural language feedback prompt words. The feedback prompt words contain a set of allowed graph rewriting operations and constraint statements that keep the semantics of the input and output interfaces unchanged. The semantic rewriting engine, which integrates a large language model, is used to perform constrained graph rewriting transformations on the local subgraphs corresponding to bottleneck task nodes based on the feedback prompts to generate the corrected ATG. The iteration controller manages the iteration process and sets the maximum number of iterations. It detects oscillations and triggers a rollback or switches the rewrite strategy when the maximum number of iterations is reached or an oscillation is detected.

7. An electronic device comprising a memory and a processor, wherein the memory stores a computer program, characterized in that, When the processor executes the program, it implements the method as described in any one of claims 1-5.

8. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the program is executed by the processor, it implements the method as described in any one of claims 1-5.

9. A computer program product, comprising a computer program, characterized in that, When the computer program is executed by a processor, it implements the method as described in any one of claims 1-5.