CloverBootloader/Library/OcMiscLib/Math.c

61 lines
2.0 KiB
C
Raw Normal View History

/** @file
Copyright (C) 2019, vit9696. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include <Library/BaseLib.h>
#include <Library/OcMiscLib.h>
/**
MultThenDivU64x64x32 is from MdeModulePkg's PciRootBridgeIo.c
Copyright (c) 1999 - 2018, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
UINT64
MultThenDivU64x64x32 (
IN UINT64 Multiplicand,
IN UINT64 Multiplier,
IN UINT32 Divisor,
OUT UINT32 *Remainder OPTIONAL
)
{
UINT64 Uint64;
UINT32 LocalRemainder;
UINT32 Uint32;
if (Multiplicand > DivU64x64Remainder (MAX_UINT64, Multiplier, NULL)) {
//
// Make sure Multiplicand is the bigger one.
//
if (Multiplicand < Multiplier) {
Uint64 = Multiplicand;
Multiplicand = Multiplier;
Multiplier = Uint64;
}
//
// Because Multiplicand * Multiplier overflows,
// Multiplicand * Multiplier / Divisor
// = (2 * Multiplicand' + 1) * Multiplier / Divisor
// = 2 * (Multiplicand' * Multiplier / Divisor) + Multiplier / Divisor
//
Uint64 = MultThenDivU64x64x32 (RShiftU64 (Multiplicand, 1), Multiplier, Divisor, &LocalRemainder);
Uint64 = LShiftU64 (Uint64, 1);
Uint32 = 0;
if ((Multiplicand & 0x1) == 1) {
Uint64 += DivU64x32Remainder (Multiplier, Divisor, &Uint32);
}
return Uint64 + DivU64x32Remainder (Uint32 + LShiftU64 (LocalRemainder, 1), Divisor, Remainder);
} else {
return DivU64x32Remainder (MultU64x64 (Multiplicand, Multiplier), Divisor, Remainder);
}
}