Computer system simulators are important tools for research and prototype development of embedded systems. For interpretation-based simulators, the decoding process of CPU models has an important effect on their performance. Therefore, improving the performance of the decoding process is one of the key problems of simulation efficiency. Besides, for instruction sets without a standard test suite (such as custom instructions), writing functional tests manually leads to low development efficiency. The instruction information required by functional tests is practically the same as the implementation of the decoding process. To solve the above problems, we propose a code generation method, which takes an instruction set description as input and outputs its implementation codes optimized for gem5 and its functional tests. Firstly, we extend the instruction set description language of gem5 and divide it into code description, function description, and test description. Secondly, we optimize the construction algorithm of decoding decision trees for gem5 and generate decoding codes, instruction codes, and functional test cases. Lastly, we take the Cortex-M3 instruction set as an example and compare our method with the original method of gem5. The total generation time is reduced by about 64%, the compiled executable code size is reduced by about 407 KB, the performance is improved by about 13%, and our method can improve the development efficiency.