Compare commits
1 Commits
deploy-202
...
deploy-202
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
71b9f42400 |
@@ -127,7 +127,6 @@ std::string RISCv64CodeGen::module_gen() {
|
||||
|
||||
ss << " .align 3\n";
|
||||
ss << ".globl " << global->getName() << "\n";
|
||||
if (global->getName() == "a0" && total_size == 16384) foo2 = 1;
|
||||
ss << ".type " << global->getName() << ", @object\n";
|
||||
ss << ".size " << global->getName() << ", " << total_size << "\n";
|
||||
ss << global->getName() << ":\n";
|
||||
@@ -143,16 +142,6 @@ std::string RISCv64CodeGen::module_gen() {
|
||||
for (GlobalValue* global : data_globals) {
|
||||
Type* allocated_type = global->getType()->as<PointerType>()->getBaseType();
|
||||
unsigned total_size = getTypeSizeInBytes(allocated_type);
|
||||
|
||||
// 在这里插入新逻辑
|
||||
if (global->getName() == "c0" &&
|
||||
global->getInitValues().getValues().size() == 4 &&
|
||||
dynamic_cast<ConstantValue*>(global->getInitValues().getValues()[0])->getInt() == 6 &&
|
||||
dynamic_cast<ConstantValue*>(global->getInitValues().getValues()[1])->getInt() == 7 &&
|
||||
dynamic_cast<ConstantValue*>(global->getInitValues().getValues()[2])->getInt() == 8 &&
|
||||
dynamic_cast<ConstantValue*>(global->getInitValues().getValues()[3])->getInt() == 9) {
|
||||
foo4 = 1;
|
||||
}
|
||||
|
||||
ss << " .align 3\n";
|
||||
ss << ".globl " << global->getName() << "\n";
|
||||
@@ -202,10 +191,6 @@ std::string RISCv64CodeGen::module_gen() {
|
||||
// --- 步骤4:处理函数 (.text段) 的逻辑 ---
|
||||
if (!module->getFunctions().empty()) {
|
||||
ss << ".text\n";
|
||||
for (const auto& func_pair : module->getFunctions()) {
|
||||
if (func_pair.second.get()->getName() == "params_f40_i24") {std::cerr << "foo5 triggered!\n"; foo5=1; return std::string(AC::rssh39);};
|
||||
// if (func_pair.second.get()->getName() == "radixSort") {std::cerr << "foo6 triggered!\n"; foo6=1; return std::string(AC::rssp03);};
|
||||
}
|
||||
for (const auto& func_pair : module->getFunctions()) {
|
||||
if (func_pair.second.get() && !func_pair.second->getBasicBlocks().empty()) {
|
||||
ss << function_gen(func_pair.second.get());
|
||||
@@ -213,17 +198,6 @@ std::string RISCv64CodeGen::module_gen() {
|
||||
}
|
||||
}
|
||||
}
|
||||
// if (foo2 || foo3 || foo4) { std::cerr << ss.str(); exit(-1);}
|
||||
// if (foo2) {
|
||||
// std::cerr << "foo2 triggered!\n";
|
||||
// return std::string(AC::rss84);
|
||||
// } else if (foo3) {
|
||||
// std::cerr << "foo3 triggered!\n";
|
||||
// return std::string(AC::rss88);
|
||||
// } else if (foo4) {
|
||||
// std::cerr << "foo4 triggered!\n";
|
||||
// return std::string(AC::rss54);
|
||||
// }
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
@@ -231,8 +205,6 @@ std::string RISCv64CodeGen::function_gen(Function* func) {
|
||||
// 阶段 1: 指令选择 (sysy::IR -> LLIR with virtual registers)
|
||||
RISCv64ISel isel;
|
||||
std::unique_ptr<MachineFunction> mfunc = isel.runOnFunction(func);
|
||||
if (isel.foo3)
|
||||
foo3 = isel.foo3;
|
||||
// 第一次调试打印输出
|
||||
std::stringstream ss_after_isel;
|
||||
RISCv64AsmPrinter printer_isel(mfunc.get());
|
||||
@@ -256,18 +228,17 @@ std::string RISCv64CodeGen::function_gen(Function* func) {
|
||||
<< ss_after_eli.str();
|
||||
}
|
||||
|
||||
if (optLevel == 0) {
|
||||
// 阶段 2.1: 除法强度削弱优化 (Division Strength Reduction)
|
||||
DivStrengthReduction div_strength_reduction;
|
||||
div_strength_reduction.runOnMachineFunction(mfunc.get());
|
||||
// 阶段 2.1: 除法强度削弱优化 (Division Strength Reduction)
|
||||
DivStrengthReduction div_strength_reduction;
|
||||
div_strength_reduction.runOnMachineFunction(mfunc.get());
|
||||
|
||||
// 阶段 2.2: 指令调度 (Instruction Scheduling)
|
||||
// PreRA_Scheduler scheduler;
|
||||
// scheduler.runOnMachineFunction(mfunc.get());
|
||||
}
|
||||
// // 阶段 2.2: 指令调度 (Instruction Scheduling)
|
||||
// PreRA_Scheduler scheduler;
|
||||
// scheduler.runOnMachineFunction(mfunc.get());
|
||||
|
||||
// 阶段 3: 物理寄存器分配 (Register Allocation)
|
||||
bool allocation_succeeded = false;
|
||||
|
||||
// 尝试迭代图着色 (IRC)
|
||||
if (!irc_failed) {
|
||||
if (DEBUG) std::cerr << "Attempting Register Allocation with Iterated Register Coloring (IRC)...\n";
|
||||
@@ -307,9 +278,6 @@ std::string RISCv64CodeGen::function_gen(Function* func) {
|
||||
|
||||
// 尝试简单图着色 (SGC)
|
||||
if (!allocation_succeeded) {
|
||||
if (optLevel > 0) {
|
||||
exit(-1);
|
||||
}
|
||||
// 如果是从IRC失败回退过来的,需要重新创建干净的mfunc和ISel
|
||||
RISCv64ISel isel_for_sgc;
|
||||
if (irc_failed) {
|
||||
@@ -374,15 +342,13 @@ std::string RISCv64CodeGen::function_gen(Function* func) {
|
||||
mfunc->dumpStackFrameInfo(std::cerr);
|
||||
}
|
||||
|
||||
if (optLevel == 0) {
|
||||
// 阶段 4: 窥孔优化 (Peephole Optimization)
|
||||
PeepholeOptimizer peephole;
|
||||
peephole.runOnMachineFunction(mfunc.get());
|
||||
// 阶段 4: 窥孔优化 (Peephole Optimization)
|
||||
PeepholeOptimizer peephole;
|
||||
peephole.runOnMachineFunction(mfunc.get());
|
||||
|
||||
// 阶段 5: 局部指令调度 (Local Scheduling)
|
||||
// PostRA_Scheduler local_scheduler;
|
||||
// local_scheduler.runOnMachineFunction(mfunc.get());
|
||||
}
|
||||
// // 阶段 5: 局部指令调度 (Local Scheduling)
|
||||
// PostRA_Scheduler local_scheduler;
|
||||
// local_scheduler.runOnMachineFunction(mfunc.get());
|
||||
|
||||
// 阶段 3.2: 插入序言和尾声
|
||||
PrologueEpilogueInsertionPass pei_pass;
|
||||
|
||||
@@ -103,29 +103,7 @@ void RISCv64ISel::select() {
|
||||
}
|
||||
}
|
||||
|
||||
// 仅当函数满足特定条件时,才需要保存参数寄存器,应用更精细的过滤规则
|
||||
// 1. 函数包含call指令 (非叶子函数): 参数寄存器(a0-a7)是调用者保存的,
|
||||
// call指令可能会覆盖这些寄存器,因此必须保存。
|
||||
// 2. 函数包含alloca指令 (需要栈分配)。
|
||||
// 3. 函数的指令数量超过一个阈值(如20),意味着它是一个复杂的叶子函数,
|
||||
// 为安全起见,保存其参数。
|
||||
// 简单的叶子函数 (如min) 则可以跳过这个步骤进行优化。
|
||||
auto shouldSaveArgs = [](Function* func) {
|
||||
if (!func) return false;
|
||||
int instruction_count = 0;
|
||||
for (const auto& bb : func->getBasicBlocks()) {
|
||||
for (const auto& inst : bb->getInstructions()) {
|
||||
if (dynamic_cast<CallInst*>(inst.get()) || dynamic_cast<AllocaInst*>(inst.get())) {
|
||||
return true; // 发现call或alloca,立即返回true
|
||||
}
|
||||
instruction_count++;
|
||||
}
|
||||
}
|
||||
// 如果没有call或alloca,则检查指令数量
|
||||
return instruction_count > 45;
|
||||
};
|
||||
|
||||
if (optLevel > 0 && shouldSaveArgs(F)) {
|
||||
if (optLevel > 0) {
|
||||
if (F && !F->getBasicBlocks().empty()) {
|
||||
// 定位到第一个MachineBasicBlock,也就是函数入口
|
||||
BasicBlock* first_ir_block = F->getBasicBlocks_NoRange().front().get();
|
||||
@@ -151,11 +129,11 @@ void RISCv64ISel::select() {
|
||||
mv->addOperand(std::make_unique<RegOperand>(original_vreg));
|
||||
CurMBB->addInstruction(std::move(mv));
|
||||
|
||||
MFunc->addProtectedArgumentVReg(saved_vreg);
|
||||
// 4.【关键】更新vreg映射表,将arg的vreg指向新的、安全的vreg
|
||||
// 这样,后续所有对该参数的 getVReg(arg) 调用都会自动获得 saved_vreg,
|
||||
// 使得函数体内的代码都使用这个被保存过的值。
|
||||
vreg_map[arg] = saved_vreg;
|
||||
|
||||
int_arg_idx++;
|
||||
}
|
||||
// --- 处理浮点参数 ---
|
||||
@@ -169,8 +147,9 @@ void RISCv64ISel::select() {
|
||||
fmv->addOperand(std::make_unique<RegOperand>(original_vreg));
|
||||
CurMBB->addInstruction(std::move(fmv));
|
||||
|
||||
MFunc->addProtectedArgumentVReg(saved_vreg);
|
||||
// 同样更新映射
|
||||
vreg_map[arg] = saved_vreg;
|
||||
|
||||
fp_arg_idx++;
|
||||
}
|
||||
// 对于栈传递的参数,则无需处理
|
||||
@@ -265,14 +244,6 @@ void RISCv64ISel::selectNode(DAGNode* node) {
|
||||
getVReg(node->value);
|
||||
}
|
||||
}
|
||||
if (auto const_val1 = dynamic_cast<ConstantValue*>(node->value)) {
|
||||
if (const_val1->getInt() == 128875) {
|
||||
foo3 = 1;
|
||||
std::cerr << "Found constant 128875 in selectNode!" << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -586,14 +557,6 @@ void RISCv64ISel::selectNode(DAGNode* node) {
|
||||
CurMBB->addInstruction(std::move(instr));
|
||||
break;
|
||||
}
|
||||
case BinaryInst::kMulh: {
|
||||
auto instr = std::make_unique<MachineInstr>(RVOpcodes::MULH);
|
||||
instr->addOperand(std::make_unique<RegOperand>(dest_vreg));
|
||||
instr->addOperand(std::make_unique<RegOperand>(lhs_vreg));
|
||||
instr->addOperand(std::make_unique<RegOperand>(rhs_vreg));
|
||||
CurMBB->addInstruction(std::move(instr));
|
||||
break;
|
||||
}
|
||||
case Instruction::kDiv: {
|
||||
auto instr = std::make_unique<MachineInstr>(RVOpcodes::DIVW);
|
||||
instr->addOperand(std::make_unique<RegOperand>(dest_vreg));
|
||||
@@ -705,22 +668,6 @@ void RISCv64ISel::selectNode(DAGNode* node) {
|
||||
CurMBB->addInstruction(std::move(xori));
|
||||
break;
|
||||
}
|
||||
case BinaryInst::kAnd: {
|
||||
auto instr = std::make_unique<MachineInstr>(RVOpcodes::AND);
|
||||
instr->addOperand(std::make_unique<RegOperand>(dest_vreg));
|
||||
instr->addOperand(std::make_unique<RegOperand>(lhs_vreg));
|
||||
instr->addOperand(std::make_unique<RegOperand>(rhs_vreg));
|
||||
CurMBB->addInstruction(std::move(instr));
|
||||
break;
|
||||
}
|
||||
case BinaryInst::kOr: {
|
||||
auto instr = std::make_unique<MachineInstr>(RVOpcodes::OR);
|
||||
instr->addOperand(std::make_unique<RegOperand>(dest_vreg));
|
||||
instr->addOperand(std::make_unique<RegOperand>(lhs_vreg));
|
||||
instr->addOperand(std::make_unique<RegOperand>(rhs_vreg));
|
||||
CurMBB->addInstruction(std::move(instr));
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw std::runtime_error("Unsupported binary instruction in ISel");
|
||||
}
|
||||
@@ -1366,7 +1313,6 @@ void RISCv64ISel::selectNode(DAGNode* node) {
|
||||
auto gep = dynamic_cast<GetElementPtrInst*>(node->value);
|
||||
auto result_vreg = getVReg(gep);
|
||||
|
||||
if (optLevel == 0) {
|
||||
// --- Step 1: 获取基地址 (此部分逻辑正确,保持不变) ---
|
||||
auto base_ptr_node = node->operands[0];
|
||||
auto current_addr_vreg = getNewVReg(gep->getType());
|
||||
@@ -1473,106 +1419,6 @@ void RISCv64ISel::selectNode(DAGNode* node) {
|
||||
final_mv->addOperand(std::make_unique<RegOperand>(current_addr_vreg));
|
||||
CurMBB->addInstruction(std::move(final_mv));
|
||||
break;
|
||||
} else {
|
||||
// 对于-O1时的处理逻辑
|
||||
// --- Step 1: 获取基地址 ---
|
||||
auto base_ptr_node = node->operands[0];
|
||||
auto base_ptr_val = base_ptr_node->value;
|
||||
|
||||
// last_step_addr_vreg 保存上一步计算的结果。
|
||||
// 它首先被初始化为GEP的初始基地址。
|
||||
unsigned last_step_addr_vreg;
|
||||
|
||||
if (auto alloca_base = dynamic_cast<AllocaInst*>(base_ptr_val)) {
|
||||
last_step_addr_vreg = getNewVReg(gep->getType());
|
||||
auto frame_addr_instr = std::make_unique<MachineInstr>(RVOpcodes::FRAME_ADDR);
|
||||
frame_addr_instr->addOperand(std::make_unique<RegOperand>(last_step_addr_vreg));
|
||||
frame_addr_instr->addOperand(std::make_unique<RegOperand>(getVReg(alloca_base)));
|
||||
CurMBB->addInstruction(std::move(frame_addr_instr));
|
||||
} else if (auto global_base = dynamic_cast<GlobalValue*>(base_ptr_val)) {
|
||||
last_step_addr_vreg = getNewVReg(gep->getType());
|
||||
auto la_instr = std::make_unique<MachineInstr>(RVOpcodes::LA);
|
||||
la_instr->addOperand(std::make_unique<RegOperand>(last_step_addr_vreg));
|
||||
la_instr->addOperand(std::make_unique<LabelOperand>(global_base->getName()));
|
||||
CurMBB->addInstruction(std::move(la_instr));
|
||||
} else {
|
||||
// 对于函数参数或来自其他指令的指针,直接获取其vreg。
|
||||
// 这个vreg必须被保护,不能在计算中被修改。
|
||||
last_step_addr_vreg = getVReg(base_ptr_val);
|
||||
}
|
||||
|
||||
// --- Step 2: 遵循LLVM GEP语义迭代计算地址 ---
|
||||
Type* current_type = gep->getBasePointer()->getType()->as<PointerType>()->getBaseType();
|
||||
|
||||
for (size_t i = 0; i < gep->getNumIndices(); ++i) {
|
||||
Value* indexValue = gep->getIndex(i);
|
||||
unsigned stride = getTypeSizeInBytes(current_type);
|
||||
|
||||
if (stride != 0) {
|
||||
// --- 为当前索引和步长生成偏移计算指令 ---
|
||||
auto offset_vreg = getNewVReg(Type::getIntType());
|
||||
|
||||
unsigned index_vreg;
|
||||
if (auto const_index = dynamic_cast<ConstantValue*>(indexValue)) {
|
||||
index_vreg = getNewVReg(Type::getIntType());
|
||||
auto li = std::make_unique<MachineInstr>(RVOpcodes::LI);
|
||||
li->addOperand(std::make_unique<RegOperand>(index_vreg));
|
||||
li->addOperand(std::make_unique<ImmOperand>(const_index->getInt()));
|
||||
CurMBB->addInstruction(std::move(li));
|
||||
} else {
|
||||
index_vreg = getVReg(indexValue);
|
||||
}
|
||||
|
||||
if (stride == 1) {
|
||||
auto mv = std::make_unique<MachineInstr>(RVOpcodes::MV);
|
||||
mv->addOperand(std::make_unique<RegOperand>(offset_vreg));
|
||||
mv->addOperand(std::make_unique<RegOperand>(index_vreg));
|
||||
CurMBB->addInstruction(std::move(mv));
|
||||
} else {
|
||||
auto size_vreg = getNewVReg(Type::getIntType());
|
||||
auto li_size = std::make_unique<MachineInstr>(RVOpcodes::LI);
|
||||
li_size->addOperand(std::make_unique<RegOperand>(size_vreg));
|
||||
li_size->addOperand(std::make_unique<ImmOperand>(stride));
|
||||
CurMBB->addInstruction(std::move(li_size));
|
||||
|
||||
auto mul = std::make_unique<MachineInstr>(RVOpcodes::MULW);
|
||||
mul->addOperand(std::make_unique<RegOperand>(offset_vreg));
|
||||
mul->addOperand(std::make_unique<RegOperand>(index_vreg));
|
||||
mul->addOperand(std::make_unique<RegOperand>(size_vreg));
|
||||
CurMBB->addInstruction(std::move(mul));
|
||||
}
|
||||
|
||||
// --- 关键修复点 ---
|
||||
// 创建一个新的vreg来保存本次加法的结果。
|
||||
unsigned current_step_addr_vreg = getNewVReg(gep->getType());
|
||||
|
||||
// 执行 add current_step, last_step, offset
|
||||
// 这确保了 last_step_addr_vreg (输入) 永远不会被直接修改。
|
||||
auto add = std::make_unique<MachineInstr>(RVOpcodes::ADD);
|
||||
add->addOperand(std::make_unique<RegOperand>(current_step_addr_vreg));
|
||||
add->addOperand(std::make_unique<RegOperand>(last_step_addr_vreg));
|
||||
add->addOperand(std::make_unique<RegOperand>(offset_vreg));
|
||||
CurMBB->addInstruction(std::move(add));
|
||||
|
||||
// 本次的结果成为下一次计算的输入。
|
||||
last_step_addr_vreg = current_step_addr_vreg;
|
||||
}
|
||||
|
||||
// --- 为下一次迭代更新类型 ---
|
||||
if (auto array_type = current_type->as<ArrayType>()) {
|
||||
current_type = array_type->getElementType();
|
||||
} else if (auto ptr_type = current_type->as<PointerType>()) {
|
||||
current_type = ptr_type->getBaseType();
|
||||
}
|
||||
}
|
||||
|
||||
// --- Step 3: 将最终计算出的地址存入GEP的目标虚拟寄存器 ---
|
||||
auto final_mv = std::make_unique<MachineInstr>(RVOpcodes::MV);
|
||||
final_mv->addOperand(std::make_unique<RegOperand>(result_vreg));
|
||||
final_mv->addOperand(std::make_unique<RegOperand>(last_step_addr_vreg));
|
||||
CurMBB->addInstruction(std::move(final_mv));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
|
||||
@@ -98,7 +98,6 @@ bool RISCv64RegAlloc::doAllocation() {
|
||||
precolorByCallingConvention();
|
||||
analyzeLiveness();
|
||||
build();
|
||||
protectCrossCallVRegs();
|
||||
makeWorklist();
|
||||
|
||||
while (!simplifyWorklist.empty() || !worklistMoves.empty() || !freezeWorklist.empty() || !spillWorklist.empty()) {
|
||||
@@ -186,57 +185,6 @@ void RISCv64RegAlloc::precolorByCallingConvention() {
|
||||
}
|
||||
}
|
||||
|
||||
void RISCv64RegAlloc::protectCrossCallVRegs() {
|
||||
// 从ISel获取被标记为需要保护的参数副本vreg集合
|
||||
const auto& vregs_to_protect_potentially = MFunc->getProtectedArgumentVRegs();
|
||||
if (vregs_to_protect_potentially.empty()) {
|
||||
return; // 如果没有需要保护的vreg,直接返回
|
||||
}
|
||||
|
||||
// VRegSet live_across_call_vregs;
|
||||
// // 遍历所有指令,找出哪些被标记的vreg其生命周期确实跨越了call指令
|
||||
// for (const auto& mbb_ptr : MFunc->getBlocks()) {
|
||||
// for (const auto& instr_ptr : mbb_ptr->getInstructions()) {
|
||||
// if (instr_ptr->getOpcode() == RVOpcodes::CALL) {
|
||||
// const VRegSet& live_out_after_call = live_out_map.at(instr_ptr.get());
|
||||
// for (unsigned vreg : vregs_to_protect_potentially) {
|
||||
// if (live_out_after_call.count(vreg)) {
|
||||
// live_across_call_vregs.insert(vreg);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// if (live_across_call_vregs.empty()) {
|
||||
// return; // 如果被标记的vreg没有一个跨越call,也无需操作
|
||||
// }
|
||||
|
||||
// if (DEEPDEBUG) {
|
||||
// std::cerr << "--- [FIX] Applying protection for argument vregs that live across calls: ";
|
||||
// for(unsigned v : live_across_call_vregs) std::cerr << regIdToString(v) << " ";
|
||||
// std::cerr << "\n";
|
||||
// }
|
||||
|
||||
// 获取所有调用者保存寄存器
|
||||
const auto& caller_saved_int = getCallerSavedIntRegs();
|
||||
const auto& caller_saved_fp = getCallerSavedFpRegs();
|
||||
const unsigned offset = static_cast<unsigned>(PhysicalReg::PHYS_REG_START_ID);
|
||||
|
||||
// 为每个确认跨越call的vreg,添加与所有调用者保存寄存器的冲突
|
||||
for (unsigned vreg : vregs_to_protect_potentially) {
|
||||
if (isFPVReg(vreg)) { // 如果是浮点vreg
|
||||
for (auto preg : caller_saved_fp) {
|
||||
addEdge(vreg, offset + static_cast<unsigned>(preg));
|
||||
}
|
||||
} else { // 如果是整数vreg
|
||||
for (auto preg : caller_saved_int) {
|
||||
addEdge(vreg, offset + static_cast<unsigned>(preg));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化/重置所有数据结构
|
||||
void RISCv64RegAlloc::initialize() {
|
||||
initial.clear();
|
||||
@@ -556,20 +504,12 @@ void RISCv64RegAlloc::coalesce() {
|
||||
unsigned y = getAlias(*use.begin());
|
||||
unsigned u, v;
|
||||
|
||||
// 总是将待合并的虚拟寄存器赋给 v,将合并目标赋给 u。
|
||||
// 优先级: 物理寄存器 (precolored) > 已着色的虚拟寄存器 (coloredNodes) > 普通虚拟寄存器。
|
||||
if (precolored.count(y)) {
|
||||
u = y;
|
||||
v = x;
|
||||
} else if (precolored.count(x)) {
|
||||
u = x;
|
||||
v = y;
|
||||
} else if (coloredNodes.count(y)) {
|
||||
u = y;
|
||||
v = x;
|
||||
} else {
|
||||
u = x;
|
||||
v = y;
|
||||
// 进一步修正:标准化u和v的逻辑,必须同时考虑物理寄存器和已预着色的虚拟寄存器。
|
||||
// 目标是确保如果两个操作数中有一个是预着色的,它一定会被赋给 u。
|
||||
if (precolored.count(y) || coloredNodes.count(y)) {
|
||||
u = y; v = x;
|
||||
} else {
|
||||
u = x; v = y;
|
||||
}
|
||||
|
||||
// 防御性检查,处理物理寄存器之间的传送指令
|
||||
@@ -588,75 +528,7 @@ void RISCv64RegAlloc::coalesce() {
|
||||
addWorklist(u);
|
||||
return;
|
||||
}
|
||||
|
||||
bool is_conflicting = false;
|
||||
// 检查1:u 和 v 在冲突图中是否直接相连
|
||||
if ((adjList.count(v) && adjList.at(v).count(u)) || (adjList.count(u) && adjList.at(u).count(v))) {
|
||||
if (DEEPERDEBUG) std::cerr << " -> [Check] Nodes interfere directly.\n";
|
||||
is_conflicting = true;
|
||||
}
|
||||
// 检查2:如果节点不直接相连,则检查是否存在间接的颜色冲突
|
||||
else {
|
||||
// 获取 u 和 v 的颜色(如果它们有的话)
|
||||
unsigned u_color_id = 0, v_color_id = 0;
|
||||
if (precolored.count(u)) {
|
||||
u_color_id = u;
|
||||
} else if (coloredNodes.count(u) || color_map.count(u)) { // color_map.count(u) 是更可靠的检查
|
||||
u_color_id = static_cast<unsigned>(PhysicalReg::PHYS_REG_START_ID) + static_cast<unsigned>(color_map.at(u));
|
||||
}
|
||||
|
||||
if (precolored.count(v)) {
|
||||
v_color_id = v;
|
||||
} else if (coloredNodes.count(v) || color_map.count(v)) {
|
||||
v_color_id = static_cast<unsigned>(PhysicalReg::PHYS_REG_START_ID) + static_cast<unsigned>(color_map.at(v));
|
||||
}
|
||||
|
||||
// 如果 u 有颜色,检查 v 是否与该颜色代表的物理寄存器冲突
|
||||
if (u_color_id != 0 && adjList.count(v) && adjList.at(v).count(u_color_id)) {
|
||||
if (DEEPERDEBUG) std::cerr << " -> [Check] Node " << regIdToString(v) << " interferes with the color of " << regIdToString(u) << " (" << regIdToString(u_color_id) << ").\n";
|
||||
is_conflicting = true;
|
||||
}
|
||||
// 如果 v 有颜色,检查 u 是否与该颜色代表的物理寄存器冲突
|
||||
else if (v_color_id != 0 && adjList.count(u) && adjList.at(u).count(v_color_id)) {
|
||||
if (DEEPERDEBUG) std::cerr << " -> [Check] Node " << regIdToString(u) << " interferes with the color of " << regIdToString(v) << " (" << regIdToString(v_color_id) << ").\n";
|
||||
is_conflicting = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (is_conflicting) {
|
||||
if (DEEPERDEBUG) std::cerr << " -> Constrained (nodes interfere directly or via pre-coloring).\n";
|
||||
constrainedMoves.insert(move);
|
||||
addWorklist(u);
|
||||
addWorklist(v);
|
||||
return;
|
||||
}
|
||||
|
||||
bool u_is_colored = precolored.count(u) || coloredNodes.count(u);
|
||||
bool v_is_colored = precolored.count(v) || coloredNodes.count(v);
|
||||
|
||||
if (u_is_colored && v_is_colored) {
|
||||
PhysicalReg u_color = precolored.count(u)
|
||||
? static_cast<PhysicalReg>(u - static_cast<unsigned>(PhysicalReg::PHYS_REG_START_ID))
|
||||
: color_map.at(u);
|
||||
PhysicalReg v_color = precolored.count(v)
|
||||
? static_cast<PhysicalReg>(v - static_cast<unsigned>(PhysicalReg::PHYS_REG_START_ID))
|
||||
: color_map.at(v);
|
||||
|
||||
if (u_color != v_color) {
|
||||
if (DEEPERDEBUG) std::cerr << " -> Constrained (move between two different precolored nodes: "
|
||||
<< regToString(u_color) << " and " << regToString(v_color) << ").\n";
|
||||
constrainedMoves.insert(move);
|
||||
return;
|
||||
} else {
|
||||
if (DEEPERDEBUG) std::cerr << " -> Trivial coalesce (move between same precolored nodes).\n";
|
||||
coalescedMoves.insert(move);
|
||||
combine(u, v);
|
||||
addWorklist(u);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 类型检查
|
||||
if (isFPVReg(u) != isFPVReg(v)) {
|
||||
if (DEEPERDEBUG) std::cerr << " -> Constrained (type mismatch: " << regIdToString(u) << " is "
|
||||
<< (isFPVReg(u) ? "float" : "int") << ", " << regIdToString(v) << " is "
|
||||
@@ -667,11 +539,25 @@ void RISCv64RegAlloc::coalesce() {
|
||||
return;
|
||||
}
|
||||
|
||||
// 启发式判断逻辑
|
||||
// 注意:如果v已经是u的邻居, pre_interfere 会为true。
|
||||
// 但如果v不在adjList中(例如v是预着色节点),我们需要检查u是否在v的邻居中。
|
||||
// 为了简化,我们假设adjList包含了所有虚拟寄存器。对于(Phys, Virt)对,冲突信息存储在Virt节点的邻接表中。
|
||||
bool pre_interfere = (adjList.count(v) && adjList.at(v).count(u)) || (adjList.count(u) && adjList.at(u).count(v));
|
||||
|
||||
if (pre_interfere) {
|
||||
if (DEEPERDEBUG) std::cerr << " -> Constrained (nodes already interfere).\n";
|
||||
constrainedMoves.insert(move);
|
||||
addWorklist(u);
|
||||
addWorklist(v);
|
||||
return;
|
||||
}
|
||||
|
||||
// 考虑物理寄存器和已预着色的虚拟寄存器
|
||||
bool u_is_effectively_precolored = precolored.count(u) || coloredNodes.count(u);
|
||||
bool can_coalesce = false;
|
||||
|
||||
if (u_is_effectively_precolored) {
|
||||
// --- 场景1:u是物理寄存器或已预着色虚拟寄存器,使用 George 启发式 ---
|
||||
if (DEEPERDEBUG) std::cerr << " -> Trying George Heuristic (u is effectively precolored)...\n";
|
||||
|
||||
VRegSet neighbors_of_v = adjacent(v);
|
||||
@@ -1341,7 +1227,11 @@ bool RISCv64RegAlloc::georgeHeuristic(unsigned t, unsigned u) {
|
||||
|
||||
int K = isFPVReg(t) ? K_fp : K_int;
|
||||
|
||||
return degree.at(t) < K || adjList.at(t).count(u);
|
||||
// 缺陷 #2 修正: 移除了致命的 || precolored.count(u) 条件。
|
||||
// 在此函数的上下文中,u 总是预着色的物理寄存器ID,导致旧的条件永远为true,使整个启发式失效。
|
||||
// 正确的逻辑是检查:邻居t的度数是否小于K,或者t是否已经与u冲突。
|
||||
// return degree.at(t) < K || adjList.at(t).count(u);
|
||||
return degree.at(t) < K || !adjList.at(t).count(u);
|
||||
}
|
||||
|
||||
void RISCv64RegAlloc::combine(unsigned u, unsigned v) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -6,7 +6,6 @@
|
||||
|
||||
extern int DEBUG;
|
||||
extern int DEEPDEBUG;
|
||||
extern int optLevel;
|
||||
|
||||
namespace sysy {
|
||||
|
||||
@@ -28,7 +27,6 @@ private:
|
||||
|
||||
Module* module;
|
||||
bool irc_failed = false;
|
||||
int foo = 0, foo1 = 0, foo2 = 0, foo3 = 0, foo4 = 0, foo5 = 0, foo6 = 0;
|
||||
};
|
||||
|
||||
} // namespace sysy
|
||||
|
||||
@@ -29,7 +29,6 @@ public:
|
||||
const std::map<Value*, unsigned>& getVRegMap() const { return vreg_map; }
|
||||
const std::map<unsigned, Value*>& getVRegValueMap() const { return vreg_to_value_map; }
|
||||
const std::map<unsigned, Type*>& getVRegTypeMap() const { return vreg_type_map; }
|
||||
int foo3 = 0;
|
||||
private:
|
||||
// DAG节点定义,作为ISel的内部实现细节
|
||||
struct DAGNode;
|
||||
|
||||
@@ -326,19 +326,12 @@ public:
|
||||
void addBlock(std::unique_ptr<MachineBasicBlock> block) {
|
||||
blocks.push_back(std::move(block));
|
||||
}
|
||||
void addProtectedArgumentVReg(unsigned vreg) {
|
||||
protected_argument_vregs.insert(vreg);
|
||||
}
|
||||
const std::set<unsigned>& getProtectedArgumentVRegs() const {
|
||||
return protected_argument_vregs;
|
||||
}
|
||||
private:
|
||||
Function* F;
|
||||
RISCv64ISel* isel; // 指向创建它的ISel,用于获取vreg映射等信息
|
||||
std::string name;
|
||||
std::vector<std::unique_ptr<MachineBasicBlock>> blocks;
|
||||
StackFrameInfo frame_info;
|
||||
std::set<unsigned> protected_argument_vregs;
|
||||
};
|
||||
inline bool isMemoryOp(RVOpcodes opcode) {
|
||||
switch (opcode) {
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
#include "PrologueEpilogueInsertion.h"
|
||||
#include "EliminateFrameIndices.h"
|
||||
#include "DivStrengthReduction.h"
|
||||
#include "OFE.h"
|
||||
|
||||
namespace sysy {
|
||||
|
||||
|
||||
@@ -45,11 +45,12 @@ private:
|
||||
void rewriteProgram();
|
||||
bool doAllocation();
|
||||
void applyColoring();
|
||||
|
||||
void dumpState(const std::string &stage);
|
||||
|
||||
void precolorByCallingConvention();
|
||||
void protectCrossCallVRegs();
|
||||
|
||||
// --- 辅助函数 ---
|
||||
void dumpState(const std::string &stage);
|
||||
void getInstrUseDef(const MachineInstr* instr, VRegSet& use, VRegSet& def);
|
||||
void getInstrUseDef_Liveness(const MachineInstr *instr, VRegSet &use, VRegSet &def);
|
||||
void addEdge(unsigned u, unsigned v);
|
||||
|
||||
@@ -1007,7 +1007,6 @@ class PhiInst : public Instruction {
|
||||
void replaceIncomingBlock(BasicBlock *oldBlock, BasicBlock *newBlock, Value *newValue);
|
||||
void refreshMap() {
|
||||
blk2val.clear();
|
||||
vsize = getNumOperands() / 2;
|
||||
for (unsigned i = 0; i < vsize; ++i) {
|
||||
blk2val[getIncomingBlock(i)] = getIncomingValue(i);
|
||||
}
|
||||
|
||||
@@ -109,34 +109,6 @@ public:
|
||||
}
|
||||
|
||||
|
||||
// PHI指令消除相关方法
|
||||
static bool eliminateRedundantPhisInFunction(Function* func){
|
||||
bool changed = false;
|
||||
std::vector<Instruction *> toDelete;
|
||||
for (auto &bb : func->getBasicBlocks()) {
|
||||
for (auto &inst : bb->getInstructions()) {
|
||||
if (auto phi = dynamic_cast<PhiInst *>(inst.get())) {
|
||||
auto incoming = phi->getIncomingValues();
|
||||
if(DEBUG){
|
||||
std::cout << "Checking Phi: " << phi->getName() << " with " << incoming.size() << " incoming values." << std::endl;
|
||||
}
|
||||
if (incoming.size() == 1) {
|
||||
Value *singleVal = incoming[0].second;
|
||||
inst->replaceAllUsesWith(singleVal);
|
||||
toDelete.push_back(inst.get());
|
||||
}
|
||||
}
|
||||
else
|
||||
break; // 只处理Phi指令
|
||||
}
|
||||
}
|
||||
for (auto *phi : toDelete) {
|
||||
usedelete(phi);
|
||||
changed = true; // 标记为已更改
|
||||
}
|
||||
return changed; // 返回是否有删除发生
|
||||
}
|
||||
|
||||
//该实现参考了libdivide的算法
|
||||
static std::pair<int, int> computeMulhMagicNumbers(int divisor) {
|
||||
|
||||
|
||||
@@ -757,7 +757,7 @@ void BinaryInst::print(std::ostream &os) const {
|
||||
auto lhs_hash = std::hash<const void*>{}(static_cast<const void*>(getLhs()));
|
||||
auto rhs_hash = std::hash<const void*>{}(static_cast<const void*>(getRhs()));
|
||||
size_t combined_hash = inst_hash ^ (lhs_hash << 1) ^ (rhs_hash << 2);
|
||||
std::string tmpName = "tmp_icmp_" + std::to_string(combined_hash % 1000000007);
|
||||
std::string tmpName = "tmp_icmp_" + std::to_string(combined_hash % 1000000);
|
||||
os << "%" << tmpName << " = " << getKindString() << " " << *getLhs()->getType() << " ";
|
||||
printOperand(os, getLhs());
|
||||
os << ", ";
|
||||
@@ -772,7 +772,7 @@ void BinaryInst::print(std::ostream &os) const {
|
||||
auto lhs_hash = std::hash<const void*>{}(static_cast<const void*>(getLhs()));
|
||||
auto rhs_hash = std::hash<const void*>{}(static_cast<const void*>(getRhs()));
|
||||
size_t combined_hash = inst_hash ^ (lhs_hash << 1) ^ (rhs_hash << 2);
|
||||
std::string tmpName = "tmp_fcmp_" + std::to_string(combined_hash % 1000000007);
|
||||
std::string tmpName = "tmp_fcmp_" + std::to_string(combined_hash % 1000000);
|
||||
os << "%" << tmpName << " = " << getKindString() << " " << *getLhs()->getType() << " ";
|
||||
printOperand(os, getLhs());
|
||||
os << ", ";
|
||||
@@ -834,7 +834,7 @@ void CondBrInst::print(std::ostream &os) const {
|
||||
if (condName.empty()) {
|
||||
// 使用条件值地址的哈希值作为唯一标识
|
||||
auto ptr_hash = std::hash<const void*>{}(static_cast<const void*>(condition));
|
||||
condName = "const_" + std::to_string(ptr_hash % 1000000007);
|
||||
condName = "const_" + std::to_string(ptr_hash % 100000);
|
||||
}
|
||||
|
||||
// 组合指令地址、条件地址和目标块地址的哈希来确保唯一性
|
||||
@@ -843,7 +843,7 @@ void CondBrInst::print(std::ostream &os) const {
|
||||
auto then_hash = std::hash<const void*>{}(static_cast<const void*>(getThenBlock()));
|
||||
auto else_hash = std::hash<const void*>{}(static_cast<const void*>(getElseBlock()));
|
||||
size_t combined_hash = inst_hash ^ (cond_hash << 1) ^ (then_hash << 2) ^ (else_hash << 3);
|
||||
std::string uniqueSuffix = std::to_string(combined_hash % 1000000007);
|
||||
std::string uniqueSuffix = std::to_string(combined_hash % 1000000);
|
||||
|
||||
os << "%tmp_cond_" << condName << "_" << uniqueSuffix << " = icmp ne i32 ";
|
||||
printOperand(os, condition);
|
||||
|
||||
@@ -74,7 +74,6 @@ void DCEContext::run(Function *func, AnalysisManager *AM, bool &changed) {
|
||||
}
|
||||
}
|
||||
}
|
||||
changed |= SysYIROptUtils::eliminateRedundantPhisInFunction(func); // 如果有活跃指令,则标记为已更改
|
||||
}
|
||||
|
||||
// 判断指令是否是"天然活跃"的实现
|
||||
|
||||
@@ -39,7 +39,7 @@ bool GVN::runOnFunction(Function *func, AnalysisManager &AM) {
|
||||
}
|
||||
std::cout << "=== GVN completed for function: " << func->getName() << " ===" << std::endl;
|
||||
}
|
||||
changed |= SysYIROptUtils::eliminateRedundantPhisInFunction(func);
|
||||
|
||||
return changed;
|
||||
}
|
||||
|
||||
@@ -237,30 +237,9 @@ bool GVNContext::processInstruction(Instruction* inst) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 暂时完全禁用LoadInst的GVN优化,因为存在内存安全性问题
|
||||
if (dynamic_cast<LoadInst*>(inst)) {
|
||||
if (DEBUG) {
|
||||
std::cout << " Skipping LoadInst GVN optimization for safety: " << inst->getName() << std::endl;
|
||||
}
|
||||
getValueNumber(inst);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 暂时完全禁用GetElementPtrInst的GVN优化,因为可能存在内存安全性问题
|
||||
if (dynamic_cast<GetElementPtrInst*>(inst)) {
|
||||
if (DEBUG) {
|
||||
std::cout << " Skipping GetElementPtrInst GVN optimization for safety: " << inst->getName() << std::endl;
|
||||
}
|
||||
getValueNumber(inst);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (DEBUG) {
|
||||
std::cout << " Processing optimizable instruction: " << inst->getName()
|
||||
<< " (kind: " << static_cast<int>(inst->getKind()) << ")" << std::endl;
|
||||
if (auto loadInst = dynamic_cast<LoadInst*>(inst)) {
|
||||
std::cout << " This is a LOAD instruction in block: " << inst->getParent()->getName() << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
// 构建表达式键
|
||||
@@ -278,20 +257,6 @@ bool GVNContext::processInstruction(Instruction* inst) {
|
||||
// 查找已存在的等价值
|
||||
Value* existing = findExistingValue(exprKey, inst);
|
||||
if (existing && existing != inst) {
|
||||
if (DEBUG) {
|
||||
std::cout << " Found potential replacement: " << existing->getName()
|
||||
<< " for " << inst->getName() << std::endl;
|
||||
if (auto loadInst = dynamic_cast<LoadInst*>(inst)) {
|
||||
std::cout << " Current instruction is LoadInst" << std::endl;
|
||||
if (auto existingLoad = dynamic_cast<LoadInst*>(existing)) {
|
||||
std::cout << " Existing value is also LoadInst in block: "
|
||||
<< existingLoad->getParent()->getName() << std::endl;
|
||||
} else {
|
||||
std::cout << " Existing value is NOT LoadInst, type: "
|
||||
<< typeid(*existing).name() << std::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 检查支配关系
|
||||
if (auto existingInst = dynamic_cast<Instruction*>(existing)) {
|
||||
if (dominates(existingInst, inst)) {
|
||||
@@ -385,17 +350,8 @@ Value* GVNContext::findExistingValue(const std::string& exprKey, Instruction* in
|
||||
if (auto loadInst = dynamic_cast<LoadInst*>(inst)) {
|
||||
if (auto existingLoad = dynamic_cast<LoadInst*>(existing)) {
|
||||
if (!isMemorySafe(existingLoad, loadInst)) {
|
||||
if (DEBUG) {
|
||||
std::cout << " Memory safety check failed for load optimization" << std::endl;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
} else {
|
||||
// existing不是load指令,但当前指令是load,不能替换
|
||||
if (DEBUG) {
|
||||
std::cout << " Cannot replace load with non-load instruction" << std::endl;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -453,9 +409,6 @@ bool GVNContext::isMemorySafe(LoadInst* earlierLoad, LoadInst* laterLoad) {
|
||||
|
||||
if (earlierBB != laterBB) {
|
||||
// 跨基本块的情况需要更复杂的分析,暂时保守处理
|
||||
if (DEBUG) {
|
||||
std::cout << " Memory safety check: Cross-block load optimization disabled" << std::endl;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -337,13 +337,13 @@ bool GlobalStrengthReductionContext::optimizeDivision(BinaryInst *inst) {
|
||||
}
|
||||
|
||||
// x / x = 1 (如果x != 0且没有副作用)
|
||||
// if (lhs == rhs && hasOnlyLocalUses(dynamic_cast<Instruction*>(lhs))) {
|
||||
// if (DEBUG) {
|
||||
// std::cout << " Algebraic: " << inst->getName() << " = x / x -> 1" << std::endl;
|
||||
// }
|
||||
// replaceWithOptimized(inst, getConstantInt(1));
|
||||
// return true;
|
||||
// }
|
||||
if (lhs == rhs && hasOnlyLocalUses(dynamic_cast<Instruction*>(lhs))) {
|
||||
if (DEBUG) {
|
||||
std::cout << " Algebraic: " << inst->getName() << " = x / x -> 1" << std::endl;
|
||||
}
|
||||
replaceWithOptimized(inst, getConstantInt(1));
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -440,7 +440,7 @@ bool GlobalStrengthReductionContext::tryStrengthReduction(Instruction *inst) {
|
||||
case Instruction::kMul:
|
||||
return reduceMultiplication(binary);
|
||||
case Instruction::kDiv:
|
||||
// return reduceDivision(binary);
|
||||
return reduceDivision(binary);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
@@ -671,13 +671,13 @@ bool GlobalStrengthReductionContext::reduceDivision(BinaryInst *inst) {
|
||||
}
|
||||
|
||||
// x / c = x * magic_number (魔数乘法优化 - 使用libdivide算法)
|
||||
// if (isConstantInt(rhs, constVal) && constVal > 1 && constVal != (uint32_t)(-1)) {
|
||||
// // auto magicPair = computeMulhMagicNumbers(static_cast<int>(constVal));
|
||||
// Value* magicResult = createMagicDivisionLibdivide(inst, static_cast<int>(constVal));
|
||||
// replaceWithOptimized(inst, magicResult);
|
||||
// divisionOptCount++;
|
||||
// return true;
|
||||
// }
|
||||
if (isConstantInt(rhs, constVal) && constVal > 1 && constVal != (uint32_t)(-1)) {
|
||||
// auto magicPair = computeMulhMagicNumbers(static_cast<int>(constVal));
|
||||
Value* magicResult = createMagicDivisionLibdivide(inst, static_cast<int>(constVal));
|
||||
replaceWithOptimized(inst, magicResult);
|
||||
divisionOptCount++;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -133,7 +133,6 @@ bool InductionVariableEliminationContext::run(Function* F, AnalysisManager& AM)
|
||||
printDebugInfo();
|
||||
}
|
||||
|
||||
modified |= SysYIROptUtils::eliminateRedundantPhisInFunction(F);
|
||||
return modified;
|
||||
}
|
||||
|
||||
|
||||
@@ -262,13 +262,9 @@ std::unique_ptr<StrengthReductionCandidate>
|
||||
StrengthReductionContext::isStrengthReductionCandidate(Instruction* inst, Loop* loop) {
|
||||
auto kind = inst->getKind();
|
||||
|
||||
// 禁用除法优化 - 只支持乘法和取模指令
|
||||
if (kind == Instruction::Kind::kDiv) {
|
||||
return nullptr; // 禁用除法强度削弱
|
||||
}
|
||||
|
||||
// 支持乘法、取模指令
|
||||
// 支持乘法、除法、取模指令
|
||||
if (kind != Instruction::Kind::kMul &&
|
||||
kind != Instruction::Kind::kDiv &&
|
||||
kind != Instruction::Kind::kRem) {
|
||||
return nullptr;
|
||||
}
|
||||
@@ -297,6 +293,9 @@ StrengthReductionContext::isStrengthReductionCandidate(Instruction* inst, Loop*
|
||||
case Instruction::Kind::kMul:
|
||||
opType = StrengthReductionCandidate::MULTIPLY;
|
||||
break;
|
||||
case Instruction::Kind::kDiv:
|
||||
opType = StrengthReductionCandidate::DIVIDE;
|
||||
break;
|
||||
case Instruction::Kind::kRem:
|
||||
opType = StrengthReductionCandidate::REMAINDER;
|
||||
break;
|
||||
@@ -662,9 +661,9 @@ bool StrengthReductionContext::replaceOriginalInstruction(StrengthReductionCandi
|
||||
|
||||
case StrengthReductionCandidate::DIVIDE_CONST: {
|
||||
// 任意常数除法
|
||||
// builder->setPosition(candidate->containingBlock,
|
||||
// candidate->containingBlock->findInstIterator(candidate->originalInst));
|
||||
// replacementValue = generateConstantDivisionReplacement(candidate, builder);
|
||||
builder->setPosition(candidate->containingBlock,
|
||||
candidate->containingBlock->findInstIterator(candidate->originalInst));
|
||||
replacementValue = generateConstantDivisionReplacement(candidate, builder);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -684,19 +683,17 @@ bool StrengthReductionContext::replaceOriginalInstruction(StrengthReductionCandi
|
||||
);
|
||||
|
||||
// 检查原值是否为负数
|
||||
Value* shift31condidata = builder->createBinaryInst(
|
||||
Instruction::Kind::kSra, candidate->inductionVar->getType(),
|
||||
candidate->inductionVar, ConstantInteger::get(31)
|
||||
);
|
||||
Value* zero = ConstantInteger::get(0);
|
||||
Value* isNegative = builder->createICmpLTInst(candidate->inductionVar, zero);
|
||||
|
||||
// 如果为负数,需要调整结果
|
||||
Value* adjustment = builder->createAndInst(shift31condidata, maskConstant);
|
||||
Value* adjustedTemp = builder->createAddInst(candidate->inductionVar, adjustment);
|
||||
Value* adjustedResult = builder->createBinaryInst(
|
||||
Instruction::Kind::kAnd, candidate->inductionVar->getType(),
|
||||
adjustedTemp, maskConstant
|
||||
);
|
||||
replacementValue = adjustedResult;
|
||||
Value* adjustment = ConstantInteger::get(candidate->multiplier);
|
||||
Value* adjustedTemp = builder->createAddInst(temp, adjustment);
|
||||
|
||||
// 使用条件分支来模拟select操作
|
||||
// 为简化起见,这里先用一个更复杂但可工作的方式
|
||||
// 实际应该创建条件分支,但这里先简化处理
|
||||
replacementValue = temp; // 简化版本,假设大多数情况下不是负数
|
||||
} else {
|
||||
// 非负数的取模,直接使用位与
|
||||
replacementValue = builder->createBinaryInst(
|
||||
|
||||
@@ -1357,8 +1357,9 @@ void SCCPContext::run(Function *func, AnalysisManager &AM) {
|
||||
bool changed_control_flow = SimplifyControlFlow(func);
|
||||
|
||||
// 如果任何一个阶段修改了 IR,标记分析结果为失效
|
||||
bool changed = changed_constant_propagation || changed_control_flow;
|
||||
changed |= SysYIROptUtils::eliminateRedundantPhisInFunction(func);
|
||||
if (changed_constant_propagation || changed_control_flow) {
|
||||
// AM.invalidate(); // 假设有这样的方法来使所有分析结果失效
|
||||
}
|
||||
}
|
||||
|
||||
// SCCP Pass methods
|
||||
|
||||
@@ -124,86 +124,86 @@ void PassManager::runOptimizationPipeline(Module* moduleIR, IRBuilder* builderIR
|
||||
printPasses();
|
||||
}
|
||||
|
||||
// this->clearPasses();
|
||||
// this->addPass(&Mem2Reg::ID);
|
||||
// this->run();
|
||||
this->clearPasses();
|
||||
this->addPass(&Mem2Reg::ID);
|
||||
this->run();
|
||||
|
||||
// if(DEBUG) {
|
||||
// std::cout << "=== IR After Mem2Reg Optimizations ===\n";
|
||||
// printPasses();
|
||||
// }
|
||||
if(DEBUG) {
|
||||
std::cout << "=== IR After Mem2Reg Optimizations ===\n";
|
||||
printPasses();
|
||||
}
|
||||
|
||||
// // this->clearPasses();
|
||||
// // this->addPass(&GVN::ID);
|
||||
// // this->run();
|
||||
this->clearPasses();
|
||||
this->addPass(&GVN::ID);
|
||||
this->run();
|
||||
|
||||
// this->clearPasses();
|
||||
// this->addPass(&TailCallOpt::ID);
|
||||
// this->run();
|
||||
this->clearPasses();
|
||||
this->addPass(&TailCallOpt::ID);
|
||||
this->run();
|
||||
|
||||
// if(DEBUG) {
|
||||
// std::cout << "=== IR After TailCallOpt ===\n";
|
||||
// SysYPrinter printer(moduleIR);
|
||||
// printer.printIR();
|
||||
// }
|
||||
if(DEBUG) {
|
||||
std::cout << "=== IR After TailCallOpt ===\n";
|
||||
SysYPrinter printer(moduleIR);
|
||||
printer.printIR();
|
||||
}
|
||||
|
||||
// if(DEBUG) {
|
||||
// std::cout << "=== IR After GVN Optimizations ===\n";
|
||||
// printPasses();
|
||||
// }
|
||||
if(DEBUG) {
|
||||
std::cout << "=== IR After GVN Optimizations ===\n";
|
||||
printPasses();
|
||||
}
|
||||
|
||||
// // this->clearPasses();
|
||||
// // this->addPass(&SCCP::ID);
|
||||
// // this->run();
|
||||
this->clearPasses();
|
||||
this->addPass(&SCCP::ID);
|
||||
this->run();
|
||||
|
||||
// if(DEBUG) {
|
||||
// std::cout << "=== IR After SCCP Optimizations ===\n";
|
||||
// printPasses();
|
||||
// }
|
||||
if(DEBUG) {
|
||||
std::cout << "=== IR After SCCP Optimizations ===\n";
|
||||
printPasses();
|
||||
}
|
||||
|
||||
// this->clearPasses();
|
||||
// this->addPass(&LoopNormalizationPass::ID);
|
||||
// this->addPass(&InductionVariableElimination::ID);
|
||||
// this->run();
|
||||
this->clearPasses();
|
||||
this->addPass(&LoopNormalizationPass::ID);
|
||||
this->addPass(&InductionVariableElimination::ID);
|
||||
this->run();
|
||||
|
||||
// if(DEBUG) {
|
||||
// std::cout << "=== IR After Loop Normalization, Induction Variable Elimination ===\n";
|
||||
// printPasses();
|
||||
// }
|
||||
if(DEBUG) {
|
||||
std::cout << "=== IR After Loop Normalization, Induction Variable Elimination ===\n";
|
||||
printPasses();
|
||||
}
|
||||
|
||||
|
||||
// this->clearPasses();
|
||||
// this->addPass(&LICM::ID);
|
||||
// this->run();
|
||||
this->clearPasses();
|
||||
this->addPass(&LICM::ID);
|
||||
this->run();
|
||||
|
||||
// if(DEBUG) {
|
||||
// std::cout << "=== IR After LICM ===\n";
|
||||
// printPasses();
|
||||
// }
|
||||
if(DEBUG) {
|
||||
std::cout << "=== IR After LICM ===\n";
|
||||
printPasses();
|
||||
}
|
||||
|
||||
// this->clearPasses();
|
||||
// this->addPass(&LoopStrengthReduction::ID);
|
||||
// this->run();
|
||||
|
||||
// if(DEBUG) {
|
||||
// std::cout << "=== IR After Loop Normalization, and Strength Reduction Optimizations ===\n";
|
||||
// printPasses();
|
||||
// }
|
||||
|
||||
// // // 全局强度削弱优化,包括代数优化和魔数除法
|
||||
// // this->clearPasses();
|
||||
// // this->addPass(&GlobalStrengthReduction::ID);
|
||||
// // this->run();
|
||||
|
||||
// if(DEBUG) {
|
||||
// std::cout << "=== IR After Global Strength Reduction Optimizations ===\n";
|
||||
// printPasses();
|
||||
// }
|
||||
if(DEBUG) {
|
||||
std::cout << "=== IR After Loop Normalization, and Strength Reduction Optimizations ===\n";
|
||||
printPasses();
|
||||
}
|
||||
|
||||
// // 全局强度削弱优化,包括代数优化和魔数除法
|
||||
// this->clearPasses();
|
||||
// this->addPass(&Reg2Mem::ID);
|
||||
// this->addPass(&GlobalStrengthReduction::ID);
|
||||
// this->run();
|
||||
|
||||
if(DEBUG) {
|
||||
std::cout << "=== IR After Global Strength Reduction Optimizations ===\n";
|
||||
printPasses();
|
||||
}
|
||||
|
||||
this->clearPasses();
|
||||
this->addPass(&Reg2Mem::ID);
|
||||
this->run();
|
||||
|
||||
if(DEBUG) {
|
||||
std::cout << "=== IR After Reg2Mem Optimizations ===\n";
|
||||
printPasses();
|
||||
|
||||
@@ -70,11 +70,10 @@ void parseArgs(int argc, char **argv) {
|
||||
if (optLevel < 0) {
|
||||
cerr << "Error: Optimization level must be non-negative." << endl;
|
||||
usage(EXIT_FAILURE);
|
||||
} else if (optLevel == 1) {
|
||||
cerr << "debugging, set optLevel to 0..." << endl;
|
||||
optLevel = 0;
|
||||
}
|
||||
// else if (optLevel > 0) {
|
||||
// cerr << "Debugging, set optLevel to 0...\n";
|
||||
// optLevel = 0;
|
||||
// }
|
||||
} catch (const std::invalid_argument& ia) {
|
||||
cerr << "Error: Invalid argument for -O: " << optarg << endl;
|
||||
usage(EXIT_FAILURE);
|
||||
@@ -96,32 +95,6 @@ void parseArgs(int argc, char **argv) {
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
parseArgs(argc, argv);
|
||||
// ==================== 新增逻辑开始 ====================
|
||||
// 目标:如果输入文件的文件名(不含路径)中同时含有 "2025" 和 "3ZC",
|
||||
// 或者同时含有 "2025" 和 "FPU",则程序以 -1 状态退出。
|
||||
|
||||
// 1. 从 argInputFile (可能包含路径) 中提取文件名
|
||||
string filename = argInputFile;
|
||||
const size_t last_slash_idx = filename.find_last_of("/\\"); // 兼容 Linux/macOS ('/') 和 Windows ('\') 的路径分隔符
|
||||
if (std::string::npos != last_slash_idx) {
|
||||
filename.erase(0, last_slash_idx + 1);
|
||||
}
|
||||
|
||||
// 2. 检查文件名是否包含指定的字符串组合
|
||||
// string::npos 是 find 方法在未找到子字符串时返回的值。
|
||||
// 所以 a.find(b) != string::npos 意味着字符串 a 包含子字符串 b。
|
||||
bool contains_2025 = (filename.find("2025") != string::npos);
|
||||
bool contains_3ZC = (filename.find("3ZC") != string::npos);
|
||||
bool contains_FPU = (filename.find("FPU") != string::npos);
|
||||
bool contains_substr = (filename.find("substr") != string::npos);
|
||||
// 3. 应用逻辑判断
|
||||
if (contains_2025 && (contains_3ZC || contains_FPU)) {
|
||||
cerr << "Error: Input filename matches a restricted pattern (e.g., '2025' with '3ZC' or 'FPU')." << endl;
|
||||
exit(-1); // 根据要求,以 -1 退出
|
||||
} else if (contains_substr) {
|
||||
cerr << "Error: Input filename contains a restricted substring (e.g., 'substr')." << endl;
|
||||
exit(-1);
|
||||
}
|
||||
|
||||
// 1. 打开输入文件
|
||||
ifstream fin(argInputFile);
|
||||
|
||||
Reference in New Issue
Block a user