MCPcopy Create free account
hub / github.com/apache/arrow / AddWithOverflowCheck

Method AddWithOverflowCheck

cpp/src/gandiva/decimal_ir.cc:208–244  ·  view source on GitHub ↗

@brief Add with overflow check. Adjust x and y to the same scale, add them, and reduce sum to output scale. If there is an overflow, the sum is set to 0.

Source from the content-addressed store, hash-verified

206/// Adjust x and y to the same scale, add them, and reduce sum to output scale.
207/// If there is an overflow, the sum is set to 0.
208DecimalIR::ValueWithOverflow DecimalIR::AddWithOverflowCheck(const ValueFull& x,
209 const ValueFull& y,
210 const ValueFull& out) {
211 auto higher_scale = GetHigherScale(x.scale(), y.scale());
212 ADD_TRACE_32("AddWithOverflowCheck : higher_scale", higher_scale);
213
214 // CPP : x_scaled = IncreaseScale(x_value, higher_scale - x.scale())
215 auto x_delta = ir_builder()->CreateSub(higher_scale, x.scale());
216 auto x_scaled = IncreaseScaleWithOverflowCheck(x.value(), x_delta);
217 ADD_TRACE_128("AddWithOverflowCheck : x_scaled", x_scaled.value());
218
219 // CPP : y_scaled = IncreaseScale(y_value, higher_scale - y_scale)
220 auto y_delta = ir_builder()->CreateSub(higher_scale, y.scale());
221 auto y_scaled = IncreaseScaleWithOverflowCheck(y.value(), y_delta);
222 ADD_TRACE_128("AddWithOverflowCheck : y_scaled", y_scaled.value());
223
224 // CPP : sum = x_scaled + y_scaled
225 auto sum_ir_struct = ir_builder()->CreateCall(sadd_with_overflow_fn_,
226 {x_scaled.value(), y_scaled.value()});
227 auto sum = ValueWithOverflow::MakeFromStruct(this, sum_ir_struct);
228 ADD_TRACE_128("AddWithOverflowCheck : sum", sum.value());
229
230 // CPP : overflow ? 0 : sum / GetScaleMultiplier(max_scale - out_scale)
231 auto overflow = GetCombinedOverflow({x_scaled, y_scaled, sum});
232 ADD_TRACE_32("AddWithOverflowCheck : overflow", overflow);
233 auto then_lambda = [&] {
234 // if there is an overflow, the value returned won't be used. so, save the division.
235 return types()->i128_constant(0);
236 };
237 auto else_lambda = [&] {
238 auto reduce_scale_by = ir_builder()->CreateSub(higher_scale, out.scale());
239 return ReduceScale(sum.value(), reduce_scale_by);
240 };
241 auto sum_descaled =
242 BuildIfElse(overflow, types()->i128_type(), then_lambda, else_lambda);
243 return ValueWithOverflow(sum_descaled, overflow);
244}
245
246// This is pretty complex, so use CPP fns.
247llvm::Value* DecimalIR::AddLarge(const ValueFull& x, const ValueFull& y,

Callers

nothing calls this directly

Calls 5

ValueWithOverflowClass · 0.85
ir_builderFunction · 0.70
typesFunction · 0.70
scaleMethod · 0.45
valueMethod · 0.45

Tested by

no test coverage detected