Browse Source

Change `>>` behaviour in LLVM to prevent stupid UB

gingerBill 4 years ago
parent
commit
3359d0323a
2 changed files with 7 additions and 8 deletions
  1. 3 4
      src/ir.cpp
  2. 4 4
      src/llvm_backend.cpp

+ 3 - 4
src/ir.cpp

@@ -4642,7 +4642,6 @@ handle_op:
 			irValue *bit_size = ir_value_constant(type, exact_value_i64(8*type_size_of(type)));
 			irValue *width_test = ir_emit(proc, ir_instr_binary_op(proc, Token_Lt, bits, bit_size, t_llvm_bool));
 
-
 			irValue *zero = ir_value_constant(type, exact_value_i64(0));
 			irValue *res = ir_emit(proc, ir_instr_binary_op(proc, op, left, bits, type));
 			return ir_emit_select(proc, width_test, res, zero);
@@ -4656,11 +4655,11 @@ handle_op:
 			irValue *bits = right;
 
 			irValue *bit_size = ir_value_constant(type, exact_value_i64(8*type_size_of(type)));
-			irValue *max = ir_value_constant(type, exact_value_i64(8*type_size_of(type)-1));
 			irValue *width_test = ir_emit(proc, ir_instr_binary_op(proc, Token_Lt, bits, bit_size, t_llvm_bool));
 
-			bits = ir_emit_select(proc, width_test, bits, max);
-			return ir_emit(proc, ir_instr_binary_op(proc, op, left, bits, type));
+			irValue *zero = ir_value_constant(type, exact_value_i64(0));
+			irValue *res = ir_emit(proc, ir_instr_binary_op(proc, op, left, bits, type));
+			return ir_emit_select(proc, width_test, res, zero);
 		}
 
 	case Token_AndNot: {

+ 4 - 4
src/llvm_backend.cpp

@@ -6600,7 +6600,6 @@ handle_op:
 			LLVMValueRef bits = rhs.value;
 
 			LLVMValueRef bit_size = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
-			LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type)-1, false);
 
 			LLVMValueRef width_test = LLVMBuildICmp(p->builder, LLVMIntULT, bits, bit_size, "");
 
@@ -6617,16 +6616,17 @@ handle_op:
 			bool is_unsigned = is_type_unsigned(type);
 
 			LLVMValueRef bit_size = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
-			LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type)-1, false);
 
 			LLVMValueRef width_test = LLVMBuildICmp(p->builder, LLVMIntULT, bits, bit_size, "");
 
-			bits = LLVMBuildSelect(p->builder, width_test, bits, max, "");
 			if (is_unsigned) {
-				res.value = LLVMBuildLShr(p->builder, lhs.value, bits, "");
+				res.value = LLVMBuildLShr(p->builder, lhsval, bits, "");
 			} else {
 				res.value = LLVMBuildAShr(p->builder, lhsval, bits, "");
 			}
+
+			LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
+			res.value = LLVMBuildSelect(p->builder, width_test, res.value, zero, "");
 			return res;
 		}
 	case Token_AndNot: