diff --git a/src/include/midend/SysYIRPrinter.h b/src/include/midend/SysYIRPrinter.h index deb22c0..6bff420 100644 --- a/src/include/midend/SysYIRPrinter.h +++ b/src/include/midend/SysYIRPrinter.h @@ -15,6 +15,7 @@ public: public: void printIR(); void printGlobalVariable(); + void printGlobalConstant(); public: diff --git a/src/midend/SysYIRPrinter.cpp b/src/midend/SysYIRPrinter.cpp index 877e4ab..e2c5e17 100644 --- a/src/midend/SysYIRPrinter.cpp +++ b/src/midend/SysYIRPrinter.cpp @@ -13,6 +13,7 @@ void SysYPrinter::printIR() { //TODO: Print target datalayout and triple (minimal required by LLVM) printGlobalVariable(); + printGlobalConstant(); for (const auto &iter : functions) { if (iter.second->getName() == "main") { @@ -137,6 +138,48 @@ void SysYPrinter::printGlobalVariable() { } } + +void SysYPrinter::printGlobalConstant() { + auto &globalConstants = pModule->getConsts(); + + for (const auto &globalConstant : globalConstants) { + std::cout << "@" << globalConstant->getName() << " = global constant "; + + // 全局变量的类型是一个指针,指向其基类型 (可能是 ArrayType 或 Integer/FloatType) + auto globalVarBaseType = dynamic_cast(globalConstant->getType())->getBaseType(); + printType(globalVarBaseType); // 打印全局变量的实际类型 (例如 i32 或 [10 x i32]) + + std::cout << " "; + + // 检查是否是数组类型 (通过检查 globalVarBaseType 是否是 ArrayType) + if (globalVarBaseType->isArray()) { + // 数组初始化器 + std::cout << "["; // LLVM IR 数组初始化器格式: [type value, type value, ...] + auto values = globalConstant->getInitValues(); // 假设 getInitValues() 返回一个 ValueCounter + const std::vector &counterValues = values.getValues(); // 获取所有值 + + for (size_t i = 0; i < counterValues.size(); i++) { + if (i > 0) std::cout << ", "; + // 打印元素类型,这个元素类型应该是数组的最终元素类型,例如 i32 或 float + // 可以从 globalVarBaseType 逐层剥离得到最终元素类型,但这里简化为直接从值获取 + printType(counterValues[i]->getType()); + std::cout << " "; + printValue(counterValues[i]); + } + std::cout << "]"; + } else { + // 标量初始化器 + // 假设标量全局变量的初始化值通过 getByIndex(0) 获取 + Value* initVal = globalConstant->getByIndex(0); + printType(initVal->getType()); // 打印标量值的类型 + std::cout << " "; + printValue(initVal); // 打印标量值 + } + + std::cout << ", align 4" << std::endl; + } +} + void SysYPrinter::printBlock(BasicBlock *block) { std::cout << getBlockName(block); }