Path: blob/main/contrib/llvm-project/clang/lib/CodeGen/CGExprComplex.cpp
35233 views
//===--- CGExprComplex.cpp - Emit LLVM Code for Complex Exprs -------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This contains code to emit Expr nodes with complex types as LLVM code.9//10//===----------------------------------------------------------------------===//1112#include "CGOpenMPRuntime.h"13#include "CodeGenFunction.h"14#include "CodeGenModule.h"15#include "ConstantEmitter.h"16#include "clang/AST/StmtVisitor.h"17#include "llvm/ADT/STLExtras.h"18#include "llvm/IR/Constants.h"19#include "llvm/IR/Instructions.h"20#include "llvm/IR/MDBuilder.h"21#include "llvm/IR/Metadata.h"22#include <algorithm>23using namespace clang;24using namespace CodeGen;2526//===----------------------------------------------------------------------===//27// Complex Expression Emitter28//===----------------------------------------------------------------------===//2930namespace llvm {31extern cl::opt<bool> EnableSingleByteCoverage;32} // namespace llvm3334typedef CodeGenFunction::ComplexPairTy ComplexPairTy;3536/// Return the complex type that we are meant to emit.37static const ComplexType *getComplexType(QualType type) {38type = type.getCanonicalType();39if (const ComplexType *comp = dyn_cast<ComplexType>(type)) {40return comp;41} else {42return cast<ComplexType>(cast<AtomicType>(type)->getValueType());43}44}4546namespace {47class ComplexExprEmitter48: public StmtVisitor<ComplexExprEmitter, ComplexPairTy> {49CodeGenFunction &CGF;50CGBuilderTy &Builder;51bool IgnoreReal;52bool IgnoreImag;53bool FPHasBeenPromoted;5455public:56ComplexExprEmitter(CodeGenFunction &cgf, bool ir = false, bool ii = false)57: CGF(cgf), Builder(CGF.Builder), IgnoreReal(ir), IgnoreImag(ii),58FPHasBeenPromoted(false) {}5960//===--------------------------------------------------------------------===//61// Utilities62//===--------------------------------------------------------------------===//6364bool TestAndClearIgnoreReal() {65bool I = IgnoreReal;66IgnoreReal = false;67return I;68}69bool TestAndClearIgnoreImag() {70bool I = IgnoreImag;71IgnoreImag = false;72return I;73}7475/// EmitLoadOfLValue - Given an expression with complex type that represents a76/// value l-value, this method emits the address of the l-value, then loads77/// and returns the result.78ComplexPairTy EmitLoadOfLValue(const Expr *E) {79return EmitLoadOfLValue(CGF.EmitLValue(E), E->getExprLoc());80}8182ComplexPairTy EmitLoadOfLValue(LValue LV, SourceLocation Loc);8384/// EmitStoreOfComplex - Store the specified real/imag parts into the85/// specified value pointer.86void EmitStoreOfComplex(ComplexPairTy Val, LValue LV, bool isInit);8788/// Emit a cast from complex value Val to DestType.89ComplexPairTy EmitComplexToComplexCast(ComplexPairTy Val, QualType SrcType,90QualType DestType, SourceLocation Loc);91/// Emit a cast from scalar value Val to DestType.92ComplexPairTy EmitScalarToComplexCast(llvm::Value *Val, QualType SrcType,93QualType DestType, SourceLocation Loc);9495//===--------------------------------------------------------------------===//96// Visitor Methods97//===--------------------------------------------------------------------===//9899ComplexPairTy Visit(Expr *E) {100ApplyDebugLocation DL(CGF, E);101return StmtVisitor<ComplexExprEmitter, ComplexPairTy>::Visit(E);102}103104ComplexPairTy VisitStmt(Stmt *S) {105S->dump(llvm::errs(), CGF.getContext());106llvm_unreachable("Stmt can't have complex result type!");107}108ComplexPairTy VisitExpr(Expr *S);109ComplexPairTy VisitConstantExpr(ConstantExpr *E) {110if (llvm::Constant *Result = ConstantEmitter(CGF).tryEmitConstantExpr(E))111return ComplexPairTy(Result->getAggregateElement(0U),112Result->getAggregateElement(1U));113return Visit(E->getSubExpr());114}115ComplexPairTy VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr());}116ComplexPairTy VisitGenericSelectionExpr(GenericSelectionExpr *GE) {117return Visit(GE->getResultExpr());118}119ComplexPairTy VisitImaginaryLiteral(const ImaginaryLiteral *IL);120ComplexPairTy121VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE) {122return Visit(PE->getReplacement());123}124ComplexPairTy VisitCoawaitExpr(CoawaitExpr *S) {125return CGF.EmitCoawaitExpr(*S).getComplexVal();126}127ComplexPairTy VisitCoyieldExpr(CoyieldExpr *S) {128return CGF.EmitCoyieldExpr(*S).getComplexVal();129}130ComplexPairTy VisitUnaryCoawait(const UnaryOperator *E) {131return Visit(E->getSubExpr());132}133134ComplexPairTy emitConstant(const CodeGenFunction::ConstantEmission &Constant,135Expr *E) {136assert(Constant && "not a constant");137if (Constant.isReference())138return EmitLoadOfLValue(Constant.getReferenceLValue(CGF, E),139E->getExprLoc());140141llvm::Constant *pair = Constant.getValue();142return ComplexPairTy(pair->getAggregateElement(0U),143pair->getAggregateElement(1U));144}145146// l-values.147ComplexPairTy VisitDeclRefExpr(DeclRefExpr *E) {148if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E))149return emitConstant(Constant, E);150return EmitLoadOfLValue(E);151}152ComplexPairTy VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {153return EmitLoadOfLValue(E);154}155ComplexPairTy VisitObjCMessageExpr(ObjCMessageExpr *E) {156return CGF.EmitObjCMessageExpr(E).getComplexVal();157}158ComplexPairTy VisitArraySubscriptExpr(Expr *E) { return EmitLoadOfLValue(E); }159ComplexPairTy VisitMemberExpr(MemberExpr *ME) {160if (CodeGenFunction::ConstantEmission Constant =161CGF.tryEmitAsConstant(ME)) {162CGF.EmitIgnoredExpr(ME->getBase());163return emitConstant(Constant, ME);164}165return EmitLoadOfLValue(ME);166}167ComplexPairTy VisitOpaqueValueExpr(OpaqueValueExpr *E) {168if (E->isGLValue())169return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E),170E->getExprLoc());171return CGF.getOrCreateOpaqueRValueMapping(E).getComplexVal();172}173174ComplexPairTy VisitPseudoObjectExpr(PseudoObjectExpr *E) {175return CGF.EmitPseudoObjectRValue(E).getComplexVal();176}177178// FIXME: CompoundLiteralExpr179180ComplexPairTy EmitCast(CastKind CK, Expr *Op, QualType DestTy);181ComplexPairTy VisitImplicitCastExpr(ImplicitCastExpr *E) {182// Unlike for scalars, we don't have to worry about function->ptr demotion183// here.184if (E->changesVolatileQualification())185return EmitLoadOfLValue(E);186return EmitCast(E->getCastKind(), E->getSubExpr(), E->getType());187}188ComplexPairTy VisitCastExpr(CastExpr *E) {189if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))190CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);191if (E->changesVolatileQualification())192return EmitLoadOfLValue(E);193return EmitCast(E->getCastKind(), E->getSubExpr(), E->getType());194}195ComplexPairTy VisitCallExpr(const CallExpr *E);196ComplexPairTy VisitStmtExpr(const StmtExpr *E);197198// Operators.199ComplexPairTy VisitPrePostIncDec(const UnaryOperator *E,200bool isInc, bool isPre) {201LValue LV = CGF.EmitLValue(E->getSubExpr());202return CGF.EmitComplexPrePostIncDec(E, LV, isInc, isPre);203}204ComplexPairTy VisitUnaryPostDec(const UnaryOperator *E) {205return VisitPrePostIncDec(E, false, false);206}207ComplexPairTy VisitUnaryPostInc(const UnaryOperator *E) {208return VisitPrePostIncDec(E, true, false);209}210ComplexPairTy VisitUnaryPreDec(const UnaryOperator *E) {211return VisitPrePostIncDec(E, false, true);212}213ComplexPairTy VisitUnaryPreInc(const UnaryOperator *E) {214return VisitPrePostIncDec(E, true, true);215}216ComplexPairTy VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }217218ComplexPairTy VisitUnaryPlus(const UnaryOperator *E,219QualType PromotionType = QualType());220ComplexPairTy VisitPlus(const UnaryOperator *E, QualType PromotionType);221ComplexPairTy VisitUnaryMinus(const UnaryOperator *E,222QualType PromotionType = QualType());223ComplexPairTy VisitMinus(const UnaryOperator *E, QualType PromotionType);224ComplexPairTy VisitUnaryNot (const UnaryOperator *E);225// LNot,Real,Imag never return complex.226ComplexPairTy VisitUnaryExtension(const UnaryOperator *E) {227return Visit(E->getSubExpr());228}229ComplexPairTy VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {230CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);231return Visit(DAE->getExpr());232}233ComplexPairTy VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {234CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);235return Visit(DIE->getExpr());236}237ComplexPairTy VisitExprWithCleanups(ExprWithCleanups *E) {238CodeGenFunction::RunCleanupsScope Scope(CGF);239ComplexPairTy Vals = Visit(E->getSubExpr());240// Defend against dominance problems caused by jumps out of expression241// evaluation through the shared cleanup block.242Scope.ForceCleanup({&Vals.first, &Vals.second});243return Vals;244}245ComplexPairTy VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {246assert(E->getType()->isAnyComplexType() && "Expected complex type!");247QualType Elem = E->getType()->castAs<ComplexType>()->getElementType();248llvm::Constant *Null = llvm::Constant::getNullValue(CGF.ConvertType(Elem));249return ComplexPairTy(Null, Null);250}251ComplexPairTy VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {252assert(E->getType()->isAnyComplexType() && "Expected complex type!");253QualType Elem = E->getType()->castAs<ComplexType>()->getElementType();254llvm::Constant *Null =255llvm::Constant::getNullValue(CGF.ConvertType(Elem));256return ComplexPairTy(Null, Null);257}258259struct BinOpInfo {260ComplexPairTy LHS;261ComplexPairTy RHS;262QualType Ty; // Computation Type.263FPOptions FPFeatures;264};265266BinOpInfo EmitBinOps(const BinaryOperator *E,267QualType PromotionTy = QualType());268ComplexPairTy EmitPromoted(const Expr *E, QualType PromotionTy);269ComplexPairTy EmitPromotedComplexOperand(const Expr *E, QualType PromotionTy);270LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,271ComplexPairTy (ComplexExprEmitter::*Func)272(const BinOpInfo &),273RValue &Val);274ComplexPairTy EmitCompoundAssign(const CompoundAssignOperator *E,275ComplexPairTy (ComplexExprEmitter::*Func)276(const BinOpInfo &));277278ComplexPairTy EmitBinAdd(const BinOpInfo &Op);279ComplexPairTy EmitBinSub(const BinOpInfo &Op);280ComplexPairTy EmitBinMul(const BinOpInfo &Op);281ComplexPairTy EmitBinDiv(const BinOpInfo &Op);282ComplexPairTy EmitAlgebraicDiv(llvm::Value *A, llvm::Value *B, llvm::Value *C,283llvm::Value *D);284ComplexPairTy EmitRangeReductionDiv(llvm::Value *A, llvm::Value *B,285llvm::Value *C, llvm::Value *D);286287ComplexPairTy EmitComplexBinOpLibCall(StringRef LibCallName,288const BinOpInfo &Op);289290QualType GetHigherPrecisionFPType(QualType ElementType) {291const auto *CurrentBT = cast<BuiltinType>(ElementType);292switch (CurrentBT->getKind()) {293case BuiltinType::Kind::Float16:294return CGF.getContext().FloatTy;295case BuiltinType::Kind::Float:296case BuiltinType::Kind::BFloat16:297return CGF.getContext().DoubleTy;298case BuiltinType::Kind::Double:299return CGF.getContext().LongDoubleTy;300default:301return ElementType;302}303}304305QualType HigherPrecisionTypeForComplexArithmetic(QualType ElementType,306bool IsDivOpCode) {307QualType HigherElementType = GetHigherPrecisionFPType(ElementType);308const llvm::fltSemantics &ElementTypeSemantics =309CGF.getContext().getFloatTypeSemantics(ElementType);310const llvm::fltSemantics &HigherElementTypeSemantics =311CGF.getContext().getFloatTypeSemantics(HigherElementType);312// Check that the promoted type can handle the intermediate values without313// overflowing. This can be interpreted as:314// (SmallerType.LargestFiniteVal * SmallerType.LargestFiniteVal) * 2 <=315// LargerType.LargestFiniteVal.316// In terms of exponent it gives this formula:317// (SmallerType.LargestFiniteVal * SmallerType.LargestFiniteVal318// doubles the exponent of SmallerType.LargestFiniteVal)319if (llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 <=320llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) {321FPHasBeenPromoted = true;322return CGF.getContext().getComplexType(HigherElementType);323} else {324DiagnosticsEngine &Diags = CGF.CGM.getDiags();325Diags.Report(diag::warn_next_larger_fp_type_same_size_than_fp);326return QualType();327}328}329330QualType getPromotionType(FPOptionsOverride Features, QualType Ty,331bool IsDivOpCode = false) {332if (auto *CT = Ty->getAs<ComplexType>()) {333QualType ElementType = CT->getElementType();334bool IsFloatingType = ElementType->isFloatingType();335bool IsComplexRangePromoted = CGF.getLangOpts().getComplexRange() ==336LangOptions::ComplexRangeKind::CX_Promoted;337bool HasNoComplexRangeOverride = !Features.hasComplexRangeOverride();338bool HasMatchingComplexRange = Features.hasComplexRangeOverride() &&339Features.getComplexRangeOverride() ==340CGF.getLangOpts().getComplexRange();341342if (IsDivOpCode && IsFloatingType && IsComplexRangePromoted &&343(HasNoComplexRangeOverride || HasMatchingComplexRange))344return HigherPrecisionTypeForComplexArithmetic(ElementType,345IsDivOpCode);346if (ElementType.UseExcessPrecision(CGF.getContext()))347return CGF.getContext().getComplexType(CGF.getContext().FloatTy);348}349if (Ty.UseExcessPrecision(CGF.getContext()))350return CGF.getContext().FloatTy;351return QualType();352}353354#define HANDLEBINOP(OP) \355ComplexPairTy VisitBin##OP(const BinaryOperator *E) { \356QualType promotionTy = getPromotionType( \357E->getStoredFPFeaturesOrDefault(), E->getType(), \358(E->getOpcode() == BinaryOperatorKind::BO_Div) ? true : false); \359ComplexPairTy result = EmitBin##OP(EmitBinOps(E, promotionTy)); \360if (!promotionTy.isNull()) \361result = CGF.EmitUnPromotedValue(result, E->getType()); \362return result; \363}364365HANDLEBINOP(Mul)366HANDLEBINOP(Div)367HANDLEBINOP(Add)368HANDLEBINOP(Sub)369#undef HANDLEBINOP370371ComplexPairTy VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {372return Visit(E->getSemanticForm());373}374375// Compound assignments.376ComplexPairTy VisitBinAddAssign(const CompoundAssignOperator *E) {377return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinAdd);378}379ComplexPairTy VisitBinSubAssign(const CompoundAssignOperator *E) {380return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinSub);381}382ComplexPairTy VisitBinMulAssign(const CompoundAssignOperator *E) {383return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinMul);384}385ComplexPairTy VisitBinDivAssign(const CompoundAssignOperator *E) {386return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinDiv);387}388389// GCC rejects rem/and/or/xor for integer complex.390// Logical and/or always return int, never complex.391392// No comparisons produce a complex result.393394LValue EmitBinAssignLValue(const BinaryOperator *E,395ComplexPairTy &Val);396ComplexPairTy VisitBinAssign (const BinaryOperator *E);397ComplexPairTy VisitBinComma (const BinaryOperator *E);398399400ComplexPairTy401VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);402ComplexPairTy VisitChooseExpr(ChooseExpr *CE);403404ComplexPairTy VisitInitListExpr(InitListExpr *E);405406ComplexPairTy VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {407return EmitLoadOfLValue(E);408}409410ComplexPairTy VisitVAArgExpr(VAArgExpr *E);411412ComplexPairTy VisitAtomicExpr(AtomicExpr *E) {413return CGF.EmitAtomicExpr(E).getComplexVal();414}415416ComplexPairTy VisitPackIndexingExpr(PackIndexingExpr *E) {417return Visit(E->getSelectedExpr());418}419};420} // end anonymous namespace.421422//===----------------------------------------------------------------------===//423// Utilities424//===----------------------------------------------------------------------===//425426Address CodeGenFunction::emitAddrOfRealComponent(Address addr,427QualType complexType) {428return Builder.CreateStructGEP(addr, 0, addr.getName() + ".realp");429}430431Address CodeGenFunction::emitAddrOfImagComponent(Address addr,432QualType complexType) {433return Builder.CreateStructGEP(addr, 1, addr.getName() + ".imagp");434}435436/// EmitLoadOfLValue - Given an RValue reference for a complex, emit code to437/// load the real and imaginary pieces, returning them as Real/Imag.438ComplexPairTy ComplexExprEmitter::EmitLoadOfLValue(LValue lvalue,439SourceLocation loc) {440assert(lvalue.isSimple() && "non-simple complex l-value?");441if (lvalue.getType()->isAtomicType())442return CGF.EmitAtomicLoad(lvalue, loc).getComplexVal();443444Address SrcPtr = lvalue.getAddress();445bool isVolatile = lvalue.isVolatileQualified();446447llvm::Value *Real = nullptr, *Imag = nullptr;448449if (!IgnoreReal || isVolatile) {450Address RealP = CGF.emitAddrOfRealComponent(SrcPtr, lvalue.getType());451Real = Builder.CreateLoad(RealP, isVolatile, SrcPtr.getName() + ".real");452}453454if (!IgnoreImag || isVolatile) {455Address ImagP = CGF.emitAddrOfImagComponent(SrcPtr, lvalue.getType());456Imag = Builder.CreateLoad(ImagP, isVolatile, SrcPtr.getName() + ".imag");457}458459return ComplexPairTy(Real, Imag);460}461462/// EmitStoreOfComplex - Store the specified real/imag parts into the463/// specified value pointer.464void ComplexExprEmitter::EmitStoreOfComplex(ComplexPairTy Val, LValue lvalue,465bool isInit) {466if (lvalue.getType()->isAtomicType() ||467(!isInit && CGF.LValueIsSuitableForInlineAtomic(lvalue)))468return CGF.EmitAtomicStore(RValue::getComplex(Val), lvalue, isInit);469470Address Ptr = lvalue.getAddress();471Address RealPtr = CGF.emitAddrOfRealComponent(Ptr, lvalue.getType());472Address ImagPtr = CGF.emitAddrOfImagComponent(Ptr, lvalue.getType());473474Builder.CreateStore(Val.first, RealPtr, lvalue.isVolatileQualified());475Builder.CreateStore(Val.second, ImagPtr, lvalue.isVolatileQualified());476}477478479480//===----------------------------------------------------------------------===//481// Visitor Methods482//===----------------------------------------------------------------------===//483484ComplexPairTy ComplexExprEmitter::VisitExpr(Expr *E) {485CGF.ErrorUnsupported(E, "complex expression");486llvm::Type *EltTy =487CGF.ConvertType(getComplexType(E->getType())->getElementType());488llvm::Value *U = llvm::UndefValue::get(EltTy);489return ComplexPairTy(U, U);490}491492ComplexPairTy ComplexExprEmitter::493VisitImaginaryLiteral(const ImaginaryLiteral *IL) {494llvm::Value *Imag = CGF.EmitScalarExpr(IL->getSubExpr());495return ComplexPairTy(llvm::Constant::getNullValue(Imag->getType()), Imag);496}497498499ComplexPairTy ComplexExprEmitter::VisitCallExpr(const CallExpr *E) {500if (E->getCallReturnType(CGF.getContext())->isReferenceType())501return EmitLoadOfLValue(E);502503return CGF.EmitCallExpr(E).getComplexVal();504}505506ComplexPairTy ComplexExprEmitter::VisitStmtExpr(const StmtExpr *E) {507CodeGenFunction::StmtExprEvaluation eval(CGF);508Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(), true);509assert(RetAlloca.isValid() && "Expected complex return value");510return EmitLoadOfLValue(CGF.MakeAddrLValue(RetAlloca, E->getType()),511E->getExprLoc());512}513514/// Emit a cast from complex value Val to DestType.515ComplexPairTy ComplexExprEmitter::EmitComplexToComplexCast(ComplexPairTy Val,516QualType SrcType,517QualType DestType,518SourceLocation Loc) {519// Get the src/dest element type.520SrcType = SrcType->castAs<ComplexType>()->getElementType();521DestType = DestType->castAs<ComplexType>()->getElementType();522523// C99 6.3.1.6: When a value of complex type is converted to another524// complex type, both the real and imaginary parts follow the conversion525// rules for the corresponding real types.526if (Val.first)527Val.first = CGF.EmitScalarConversion(Val.first, SrcType, DestType, Loc);528if (Val.second)529Val.second = CGF.EmitScalarConversion(Val.second, SrcType, DestType, Loc);530return Val;531}532533ComplexPairTy ComplexExprEmitter::EmitScalarToComplexCast(llvm::Value *Val,534QualType SrcType,535QualType DestType,536SourceLocation Loc) {537// Convert the input element to the element type of the complex.538DestType = DestType->castAs<ComplexType>()->getElementType();539Val = CGF.EmitScalarConversion(Val, SrcType, DestType, Loc);540541// Return (realval, 0).542return ComplexPairTy(Val, llvm::Constant::getNullValue(Val->getType()));543}544545ComplexPairTy ComplexExprEmitter::EmitCast(CastKind CK, Expr *Op,546QualType DestTy) {547switch (CK) {548case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");549550// Atomic to non-atomic casts may be more than a no-op for some platforms and551// for some types.552case CK_AtomicToNonAtomic:553case CK_NonAtomicToAtomic:554case CK_NoOp:555case CK_LValueToRValue:556case CK_UserDefinedConversion:557return Visit(Op);558559case CK_LValueBitCast: {560LValue origLV = CGF.EmitLValue(Op);561Address V = origLV.getAddress().withElementType(CGF.ConvertType(DestTy));562return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy), Op->getExprLoc());563}564565case CK_LValueToRValueBitCast: {566LValue SourceLVal = CGF.EmitLValue(Op);567Address Addr =568SourceLVal.getAddress().withElementType(CGF.ConvertTypeForMem(DestTy));569LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);570DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());571return EmitLoadOfLValue(DestLV, Op->getExprLoc());572}573574case CK_BitCast:575case CK_BaseToDerived:576case CK_DerivedToBase:577case CK_UncheckedDerivedToBase:578case CK_Dynamic:579case CK_ToUnion:580case CK_ArrayToPointerDecay:581case CK_FunctionToPointerDecay:582case CK_NullToPointer:583case CK_NullToMemberPointer:584case CK_BaseToDerivedMemberPointer:585case CK_DerivedToBaseMemberPointer:586case CK_MemberPointerToBoolean:587case CK_ReinterpretMemberPointer:588case CK_ConstructorConversion:589case CK_IntegralToPointer:590case CK_PointerToIntegral:591case CK_PointerToBoolean:592case CK_ToVoid:593case CK_VectorSplat:594case CK_IntegralCast:595case CK_BooleanToSignedIntegral:596case CK_IntegralToBoolean:597case CK_IntegralToFloating:598case CK_FloatingToIntegral:599case CK_FloatingToBoolean:600case CK_FloatingCast:601case CK_CPointerToObjCPointerCast:602case CK_BlockPointerToObjCPointerCast:603case CK_AnyPointerToBlockPointerCast:604case CK_ObjCObjectLValueCast:605case CK_FloatingComplexToReal:606case CK_FloatingComplexToBoolean:607case CK_IntegralComplexToReal:608case CK_IntegralComplexToBoolean:609case CK_ARCProduceObject:610case CK_ARCConsumeObject:611case CK_ARCReclaimReturnedObject:612case CK_ARCExtendBlockObject:613case CK_CopyAndAutoreleaseBlockObject:614case CK_BuiltinFnToFnPtr:615case CK_ZeroToOCLOpaqueType:616case CK_AddressSpaceConversion:617case CK_IntToOCLSampler:618case CK_FloatingToFixedPoint:619case CK_FixedPointToFloating:620case CK_FixedPointCast:621case CK_FixedPointToBoolean:622case CK_FixedPointToIntegral:623case CK_IntegralToFixedPoint:624case CK_MatrixCast:625case CK_HLSLVectorTruncation:626case CK_HLSLArrayRValue:627llvm_unreachable("invalid cast kind for complex value");628629case CK_FloatingRealToComplex:630case CK_IntegralRealToComplex: {631CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op);632return EmitScalarToComplexCast(CGF.EmitScalarExpr(Op), Op->getType(),633DestTy, Op->getExprLoc());634}635636case CK_FloatingComplexCast:637case CK_FloatingComplexToIntegralComplex:638case CK_IntegralComplexCast:639case CK_IntegralComplexToFloatingComplex: {640CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op);641return EmitComplexToComplexCast(Visit(Op), Op->getType(), DestTy,642Op->getExprLoc());643}644}645646llvm_unreachable("unknown cast resulting in complex value");647}648649ComplexPairTy ComplexExprEmitter::VisitUnaryPlus(const UnaryOperator *E,650QualType PromotionType) {651E->hasStoredFPFeatures();652QualType promotionTy =653PromotionType.isNull()654? getPromotionType(E->getStoredFPFeaturesOrDefault(),655E->getSubExpr()->getType())656: PromotionType;657ComplexPairTy result = VisitPlus(E, promotionTy);658if (!promotionTy.isNull())659return CGF.EmitUnPromotedValue(result, E->getSubExpr()->getType());660return result;661}662663ComplexPairTy ComplexExprEmitter::VisitPlus(const UnaryOperator *E,664QualType PromotionType) {665TestAndClearIgnoreReal();666TestAndClearIgnoreImag();667if (!PromotionType.isNull())668return CGF.EmitPromotedComplexExpr(E->getSubExpr(), PromotionType);669return Visit(E->getSubExpr());670}671672ComplexPairTy ComplexExprEmitter::VisitUnaryMinus(const UnaryOperator *E,673QualType PromotionType) {674QualType promotionTy =675PromotionType.isNull()676? getPromotionType(E->getStoredFPFeaturesOrDefault(),677E->getSubExpr()->getType())678: PromotionType;679ComplexPairTy result = VisitMinus(E, promotionTy);680if (!promotionTy.isNull())681return CGF.EmitUnPromotedValue(result, E->getSubExpr()->getType());682return result;683}684ComplexPairTy ComplexExprEmitter::VisitMinus(const UnaryOperator *E,685QualType PromotionType) {686TestAndClearIgnoreReal();687TestAndClearIgnoreImag();688ComplexPairTy Op;689if (!PromotionType.isNull())690Op = CGF.EmitPromotedComplexExpr(E->getSubExpr(), PromotionType);691else692Op = Visit(E->getSubExpr());693694llvm::Value *ResR, *ResI;695if (Op.first->getType()->isFloatingPointTy()) {696ResR = Builder.CreateFNeg(Op.first, "neg.r");697ResI = Builder.CreateFNeg(Op.second, "neg.i");698} else {699ResR = Builder.CreateNeg(Op.first, "neg.r");700ResI = Builder.CreateNeg(Op.second, "neg.i");701}702return ComplexPairTy(ResR, ResI);703}704705ComplexPairTy ComplexExprEmitter::VisitUnaryNot(const UnaryOperator *E) {706TestAndClearIgnoreReal();707TestAndClearIgnoreImag();708// ~(a+ib) = a + i*-b709ComplexPairTy Op = Visit(E->getSubExpr());710llvm::Value *ResI;711if (Op.second->getType()->isFloatingPointTy())712ResI = Builder.CreateFNeg(Op.second, "conj.i");713else714ResI = Builder.CreateNeg(Op.second, "conj.i");715716return ComplexPairTy(Op.first, ResI);717}718719ComplexPairTy ComplexExprEmitter::EmitBinAdd(const BinOpInfo &Op) {720llvm::Value *ResR, *ResI;721722if (Op.LHS.first->getType()->isFloatingPointTy()) {723CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op.FPFeatures);724ResR = Builder.CreateFAdd(Op.LHS.first, Op.RHS.first, "add.r");725if (Op.LHS.second && Op.RHS.second)726ResI = Builder.CreateFAdd(Op.LHS.second, Op.RHS.second, "add.i");727else728ResI = Op.LHS.second ? Op.LHS.second : Op.RHS.second;729assert(ResI && "Only one operand may be real!");730} else {731ResR = Builder.CreateAdd(Op.LHS.first, Op.RHS.first, "add.r");732assert(Op.LHS.second && Op.RHS.second &&733"Both operands of integer complex operators must be complex!");734ResI = Builder.CreateAdd(Op.LHS.second, Op.RHS.second, "add.i");735}736return ComplexPairTy(ResR, ResI);737}738739ComplexPairTy ComplexExprEmitter::EmitBinSub(const BinOpInfo &Op) {740llvm::Value *ResR, *ResI;741if (Op.LHS.first->getType()->isFloatingPointTy()) {742CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op.FPFeatures);743ResR = Builder.CreateFSub(Op.LHS.first, Op.RHS.first, "sub.r");744if (Op.LHS.second && Op.RHS.second)745ResI = Builder.CreateFSub(Op.LHS.second, Op.RHS.second, "sub.i");746else747ResI = Op.LHS.second ? Op.LHS.second748: Builder.CreateFNeg(Op.RHS.second, "sub.i");749assert(ResI && "Only one operand may be real!");750} else {751ResR = Builder.CreateSub(Op.LHS.first, Op.RHS.first, "sub.r");752assert(Op.LHS.second && Op.RHS.second &&753"Both operands of integer complex operators must be complex!");754ResI = Builder.CreateSub(Op.LHS.second, Op.RHS.second, "sub.i");755}756return ComplexPairTy(ResR, ResI);757}758759/// Emit a libcall for a binary operation on complex types.760ComplexPairTy ComplexExprEmitter::EmitComplexBinOpLibCall(StringRef LibCallName,761const BinOpInfo &Op) {762CallArgList Args;763Args.add(RValue::get(Op.LHS.first),764Op.Ty->castAs<ComplexType>()->getElementType());765Args.add(RValue::get(Op.LHS.second),766Op.Ty->castAs<ComplexType>()->getElementType());767Args.add(RValue::get(Op.RHS.first),768Op.Ty->castAs<ComplexType>()->getElementType());769Args.add(RValue::get(Op.RHS.second),770Op.Ty->castAs<ComplexType>()->getElementType());771772// We *must* use the full CG function call building logic here because the773// complex type has special ABI handling. We also should not forget about774// special calling convention which may be used for compiler builtins.775776// We create a function qualified type to state that this call does not have777// any exceptions.778FunctionProtoType::ExtProtoInfo EPI;779EPI = EPI.withExceptionSpec(780FunctionProtoType::ExceptionSpecInfo(EST_BasicNoexcept));781SmallVector<QualType, 4> ArgsQTys(7824, Op.Ty->castAs<ComplexType>()->getElementType());783QualType FQTy = CGF.getContext().getFunctionType(Op.Ty, ArgsQTys, EPI);784const CGFunctionInfo &FuncInfo = CGF.CGM.getTypes().arrangeFreeFunctionCall(785Args, cast<FunctionType>(FQTy.getTypePtr()), false);786787llvm::FunctionType *FTy = CGF.CGM.getTypes().GetFunctionType(FuncInfo);788llvm::FunctionCallee Func = CGF.CGM.CreateRuntimeFunction(789FTy, LibCallName, llvm::AttributeList(), true);790CGCallee Callee = CGCallee::forDirect(Func, FQTy->getAs<FunctionProtoType>());791792llvm::CallBase *Call;793RValue Res = CGF.EmitCall(FuncInfo, Callee, ReturnValueSlot(), Args, &Call);794Call->setCallingConv(CGF.CGM.getRuntimeCC());795return Res.getComplexVal();796}797798/// Lookup the libcall name for a given floating point type complex799/// multiply.800static StringRef getComplexMultiplyLibCallName(llvm::Type *Ty) {801switch (Ty->getTypeID()) {802default:803llvm_unreachable("Unsupported floating point type!");804case llvm::Type::HalfTyID:805return "__mulhc3";806case llvm::Type::FloatTyID:807return "__mulsc3";808case llvm::Type::DoubleTyID:809return "__muldc3";810case llvm::Type::PPC_FP128TyID:811return "__multc3";812case llvm::Type::X86_FP80TyID:813return "__mulxc3";814case llvm::Type::FP128TyID:815return "__multc3";816}817}818819// See C11 Annex G.5.1 for the semantics of multiplicative operators on complex820// typed values.821ComplexPairTy ComplexExprEmitter::EmitBinMul(const BinOpInfo &Op) {822using llvm::Value;823Value *ResR, *ResI;824llvm::MDBuilder MDHelper(CGF.getLLVMContext());825826if (Op.LHS.first->getType()->isFloatingPointTy()) {827// The general formulation is:828// (a + ib) * (c + id) = (a * c - b * d) + i(a * d + b * c)829//830// But we can fold away components which would be zero due to a real831// operand according to C11 Annex G.5.1p2.832833CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op.FPFeatures);834if (Op.LHS.second && Op.RHS.second) {835// If both operands are complex, emit the core math directly, and then836// test for NaNs. If we find NaNs in the result, we delegate to a libcall837// to carefully re-compute the correct infinity representation if838// possible. The expectation is that the presence of NaNs here is839// *extremely* rare, and so the cost of the libcall is almost irrelevant.840// This is good, because the libcall re-computes the core multiplication841// exactly the same as we do here and re-tests for NaNs in order to be842// a generic complex*complex libcall.843844// First compute the four products.845Value *AC = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul_ac");846Value *BD = Builder.CreateFMul(Op.LHS.second, Op.RHS.second, "mul_bd");847Value *AD = Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul_ad");848Value *BC = Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul_bc");849850// The real part is the difference of the first two, the imaginary part is851// the sum of the second.852ResR = Builder.CreateFSub(AC, BD, "mul_r");853ResI = Builder.CreateFAdd(AD, BC, "mul_i");854855if (Op.FPFeatures.getComplexRange() == LangOptions::CX_Basic ||856Op.FPFeatures.getComplexRange() == LangOptions::CX_Improved ||857Op.FPFeatures.getComplexRange() == LangOptions::CX_Promoted)858return ComplexPairTy(ResR, ResI);859860// Emit the test for the real part becoming NaN and create a branch to861// handle it. We test for NaN by comparing the number to itself.862Value *IsRNaN = Builder.CreateFCmpUNO(ResR, ResR, "isnan_cmp");863llvm::BasicBlock *ContBB = CGF.createBasicBlock("complex_mul_cont");864llvm::BasicBlock *INaNBB = CGF.createBasicBlock("complex_mul_imag_nan");865llvm::Instruction *Branch = Builder.CreateCondBr(IsRNaN, INaNBB, ContBB);866llvm::BasicBlock *OrigBB = Branch->getParent();867868// Give hint that we very much don't expect to see NaNs.869llvm::MDNode *BrWeight = MDHelper.createUnlikelyBranchWeights();870Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);871872// Now test the imaginary part and create its branch.873CGF.EmitBlock(INaNBB);874Value *IsINaN = Builder.CreateFCmpUNO(ResI, ResI, "isnan_cmp");875llvm::BasicBlock *LibCallBB = CGF.createBasicBlock("complex_mul_libcall");876Branch = Builder.CreateCondBr(IsINaN, LibCallBB, ContBB);877Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);878879// Now emit the libcall on this slowest of the slow paths.880CGF.EmitBlock(LibCallBB);881Value *LibCallR, *LibCallI;882std::tie(LibCallR, LibCallI) = EmitComplexBinOpLibCall(883getComplexMultiplyLibCallName(Op.LHS.first->getType()), Op);884Builder.CreateBr(ContBB);885886// Finally continue execution by phi-ing together the different887// computation paths.888CGF.EmitBlock(ContBB);889llvm::PHINode *RealPHI = Builder.CreatePHI(ResR->getType(), 3, "real_mul_phi");890RealPHI->addIncoming(ResR, OrigBB);891RealPHI->addIncoming(ResR, INaNBB);892RealPHI->addIncoming(LibCallR, LibCallBB);893llvm::PHINode *ImagPHI = Builder.CreatePHI(ResI->getType(), 3, "imag_mul_phi");894ImagPHI->addIncoming(ResI, OrigBB);895ImagPHI->addIncoming(ResI, INaNBB);896ImagPHI->addIncoming(LibCallI, LibCallBB);897return ComplexPairTy(RealPHI, ImagPHI);898}899assert((Op.LHS.second || Op.RHS.second) &&900"At least one operand must be complex!");901902// If either of the operands is a real rather than a complex, the903// imaginary component is ignored when computing the real component of the904// result.905ResR = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul.rl");906907ResI = Op.LHS.second908? Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul.il")909: Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul.ir");910} else {911assert(Op.LHS.second && Op.RHS.second &&912"Both operands of integer complex operators must be complex!");913Value *ResRl = Builder.CreateMul(Op.LHS.first, Op.RHS.first, "mul.rl");914Value *ResRr = Builder.CreateMul(Op.LHS.second, Op.RHS.second, "mul.rr");915ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");916917Value *ResIl = Builder.CreateMul(Op.LHS.second, Op.RHS.first, "mul.il");918Value *ResIr = Builder.CreateMul(Op.LHS.first, Op.RHS.second, "mul.ir");919ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");920}921return ComplexPairTy(ResR, ResI);922}923924ComplexPairTy ComplexExprEmitter::EmitAlgebraicDiv(llvm::Value *LHSr,925llvm::Value *LHSi,926llvm::Value *RHSr,927llvm::Value *RHSi) {928// (a+ib) / (c+id) = ((ac+bd)/(cc+dd)) + i((bc-ad)/(cc+dd))929llvm::Value *DSTr, *DSTi;930931llvm::Value *AC = Builder.CreateFMul(LHSr, RHSr); // a*c932llvm::Value *BD = Builder.CreateFMul(LHSi, RHSi); // b*d933llvm::Value *ACpBD = Builder.CreateFAdd(AC, BD); // ac+bd934935llvm::Value *CC = Builder.CreateFMul(RHSr, RHSr); // c*c936llvm::Value *DD = Builder.CreateFMul(RHSi, RHSi); // d*d937llvm::Value *CCpDD = Builder.CreateFAdd(CC, DD); // cc+dd938939llvm::Value *BC = Builder.CreateFMul(LHSi, RHSr); // b*c940llvm::Value *AD = Builder.CreateFMul(LHSr, RHSi); // a*d941llvm::Value *BCmAD = Builder.CreateFSub(BC, AD); // bc-ad942943DSTr = Builder.CreateFDiv(ACpBD, CCpDD);944DSTi = Builder.CreateFDiv(BCmAD, CCpDD);945return ComplexPairTy(DSTr, DSTi);946}947948// EmitFAbs - Emit a call to @llvm.fabs.949static llvm::Value *EmitllvmFAbs(CodeGenFunction &CGF, llvm::Value *Value) {950llvm::Function *Func =951CGF.CGM.getIntrinsic(llvm::Intrinsic::fabs, Value->getType());952llvm::Value *Call = CGF.Builder.CreateCall(Func, Value);953return Call;954}955956// EmitRangeReductionDiv - Implements Smith's algorithm for complex division.957// SMITH, R. L. Algorithm 116: Complex division. Commun. ACM 5, 8 (1962).958ComplexPairTy ComplexExprEmitter::EmitRangeReductionDiv(llvm::Value *LHSr,959llvm::Value *LHSi,960llvm::Value *RHSr,961llvm::Value *RHSi) {962// FIXME: This could eventually be replaced by an LLVM intrinsic to963// avoid this long IR sequence.964965// (a + ib) / (c + id) = (e + if)966llvm::Value *FAbsRHSr = EmitllvmFAbs(CGF, RHSr); // |c|967llvm::Value *FAbsRHSi = EmitllvmFAbs(CGF, RHSi); // |d|968// |c| >= |d|969llvm::Value *IsR = Builder.CreateFCmpUGT(FAbsRHSr, FAbsRHSi, "abs_cmp");970971llvm::BasicBlock *TrueBB =972CGF.createBasicBlock("abs_rhsr_greater_or_equal_abs_rhsi");973llvm::BasicBlock *FalseBB =974CGF.createBasicBlock("abs_rhsr_less_than_abs_rhsi");975llvm::BasicBlock *ContBB = CGF.createBasicBlock("complex_div");976Builder.CreateCondBr(IsR, TrueBB, FalseBB);977978CGF.EmitBlock(TrueBB);979// abs(c) >= abs(d)980// r = d/c981// tmp = c + rd982// e = (a + br)/tmp983// f = (b - ar)/tmp984llvm::Value *DdC = Builder.CreateFDiv(RHSi, RHSr); // r=d/c985986llvm::Value *RD = Builder.CreateFMul(DdC, RHSi); // rd987llvm::Value *CpRD = Builder.CreateFAdd(RHSr, RD); // tmp=c+rd988989llvm::Value *T3 = Builder.CreateFMul(LHSi, DdC); // br990llvm::Value *T4 = Builder.CreateFAdd(LHSr, T3); // a+br991llvm::Value *DSTTr = Builder.CreateFDiv(T4, CpRD); // (a+br)/tmp992993llvm::Value *T5 = Builder.CreateFMul(LHSr, DdC); // ar994llvm::Value *T6 = Builder.CreateFSub(LHSi, T5); // b-ar995llvm::Value *DSTTi = Builder.CreateFDiv(T6, CpRD); // (b-ar)/tmp996Builder.CreateBr(ContBB);997998CGF.EmitBlock(FalseBB);999// abs(c) < abs(d)1000// r = c/d1001// tmp = d + rc1002// e = (ar + b)/tmp1003// f = (br - a)/tmp1004llvm::Value *CdD = Builder.CreateFDiv(RHSr, RHSi); // r=c/d10051006llvm::Value *RC = Builder.CreateFMul(CdD, RHSr); // rc1007llvm::Value *DpRC = Builder.CreateFAdd(RHSi, RC); // tmp=d+rc10081009llvm::Value *T7 = Builder.CreateFMul(LHSr, CdD); // ar1010llvm::Value *T8 = Builder.CreateFAdd(T7, LHSi); // ar+b1011llvm::Value *DSTFr = Builder.CreateFDiv(T8, DpRC); // (ar+b)/tmp10121013llvm::Value *T9 = Builder.CreateFMul(LHSi, CdD); // br1014llvm::Value *T10 = Builder.CreateFSub(T9, LHSr); // br-a1015llvm::Value *DSTFi = Builder.CreateFDiv(T10, DpRC); // (br-a)/tmp1016Builder.CreateBr(ContBB);10171018// Phi together the computation paths.1019CGF.EmitBlock(ContBB);1020llvm::PHINode *VALr = Builder.CreatePHI(DSTTr->getType(), 2);1021VALr->addIncoming(DSTTr, TrueBB);1022VALr->addIncoming(DSTFr, FalseBB);1023llvm::PHINode *VALi = Builder.CreatePHI(DSTTi->getType(), 2);1024VALi->addIncoming(DSTTi, TrueBB);1025VALi->addIncoming(DSTFi, FalseBB);1026return ComplexPairTy(VALr, VALi);1027}10281029// See C11 Annex G.5.1 for the semantics of multiplicative operators on complex1030// typed values.1031ComplexPairTy ComplexExprEmitter::EmitBinDiv(const BinOpInfo &Op) {1032llvm::Value *LHSr = Op.LHS.first, *LHSi = Op.LHS.second;1033llvm::Value *RHSr = Op.RHS.first, *RHSi = Op.RHS.second;1034llvm::Value *DSTr, *DSTi;1035if (LHSr->getType()->isFloatingPointTy()) {1036CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op.FPFeatures);1037if (!RHSi) {1038assert(LHSi && "Can have at most one non-complex operand!");10391040DSTr = Builder.CreateFDiv(LHSr, RHSr);1041DSTi = Builder.CreateFDiv(LHSi, RHSr);1042return ComplexPairTy(DSTr, DSTi);1043}1044llvm::Value *OrigLHSi = LHSi;1045if (!LHSi)1046LHSi = llvm::Constant::getNullValue(RHSi->getType());1047if (Op.FPFeatures.getComplexRange() == LangOptions::CX_Improved ||1048(Op.FPFeatures.getComplexRange() == LangOptions::CX_Promoted &&1049!FPHasBeenPromoted))1050return EmitRangeReductionDiv(LHSr, LHSi, RHSr, RHSi);1051else if (Op.FPFeatures.getComplexRange() == LangOptions::CX_Basic ||1052Op.FPFeatures.getComplexRange() == LangOptions::CX_Promoted)1053return EmitAlgebraicDiv(LHSr, LHSi, RHSr, RHSi);1054// '-ffast-math' is used in the command line but followed by an1055// '-fno-cx-limited-range' or '-fcomplex-arithmetic=full'.1056else if (Op.FPFeatures.getComplexRange() == LangOptions::CX_Full) {1057LHSi = OrigLHSi;1058// If we have a complex operand on the RHS and FastMath is not allowed, we1059// delegate to a libcall to handle all of the complexities and minimize1060// underflow/overflow cases. When FastMath is allowed we construct the1061// divide inline using the same algorithm as for integer operands.1062BinOpInfo LibCallOp = Op;1063// If LHS was a real, supply a null imaginary part.1064if (!LHSi)1065LibCallOp.LHS.second = llvm::Constant::getNullValue(LHSr->getType());10661067switch (LHSr->getType()->getTypeID()) {1068default:1069llvm_unreachable("Unsupported floating point type!");1070case llvm::Type::HalfTyID:1071return EmitComplexBinOpLibCall("__divhc3", LibCallOp);1072case llvm::Type::FloatTyID:1073return EmitComplexBinOpLibCall("__divsc3", LibCallOp);1074case llvm::Type::DoubleTyID:1075return EmitComplexBinOpLibCall("__divdc3", LibCallOp);1076case llvm::Type::PPC_FP128TyID:1077return EmitComplexBinOpLibCall("__divtc3", LibCallOp);1078case llvm::Type::X86_FP80TyID:1079return EmitComplexBinOpLibCall("__divxc3", LibCallOp);1080case llvm::Type::FP128TyID:1081return EmitComplexBinOpLibCall("__divtc3", LibCallOp);1082}1083} else {1084return EmitAlgebraicDiv(LHSr, LHSi, RHSr, RHSi);1085}1086} else {1087assert(Op.LHS.second && Op.RHS.second &&1088"Both operands of integer complex operators must be complex!");1089// (a+ib) / (c+id) = ((ac+bd)/(cc+dd)) + i((bc-ad)/(cc+dd))1090llvm::Value *Tmp1 = Builder.CreateMul(LHSr, RHSr); // a*c1091llvm::Value *Tmp2 = Builder.CreateMul(LHSi, RHSi); // b*d1092llvm::Value *Tmp3 = Builder.CreateAdd(Tmp1, Tmp2); // ac+bd10931094llvm::Value *Tmp4 = Builder.CreateMul(RHSr, RHSr); // c*c1095llvm::Value *Tmp5 = Builder.CreateMul(RHSi, RHSi); // d*d1096llvm::Value *Tmp6 = Builder.CreateAdd(Tmp4, Tmp5); // cc+dd10971098llvm::Value *Tmp7 = Builder.CreateMul(LHSi, RHSr); // b*c1099llvm::Value *Tmp8 = Builder.CreateMul(LHSr, RHSi); // a*d1100llvm::Value *Tmp9 = Builder.CreateSub(Tmp7, Tmp8); // bc-ad11011102if (Op.Ty->castAs<ComplexType>()->getElementType()->isUnsignedIntegerType()) {1103DSTr = Builder.CreateUDiv(Tmp3, Tmp6);1104DSTi = Builder.CreateUDiv(Tmp9, Tmp6);1105} else {1106DSTr = Builder.CreateSDiv(Tmp3, Tmp6);1107DSTi = Builder.CreateSDiv(Tmp9, Tmp6);1108}1109}11101111return ComplexPairTy(DSTr, DSTi);1112}11131114ComplexPairTy CodeGenFunction::EmitUnPromotedValue(ComplexPairTy result,1115QualType UnPromotionType) {1116llvm::Type *ComplexElementTy =1117ConvertType(UnPromotionType->castAs<ComplexType>()->getElementType());1118if (result.first)1119result.first =1120Builder.CreateFPTrunc(result.first, ComplexElementTy, "unpromotion");1121if (result.second)1122result.second =1123Builder.CreateFPTrunc(result.second, ComplexElementTy, "unpromotion");1124return result;1125}11261127ComplexPairTy CodeGenFunction::EmitPromotedValue(ComplexPairTy result,1128QualType PromotionType) {1129llvm::Type *ComplexElementTy =1130ConvertType(PromotionType->castAs<ComplexType>()->getElementType());1131if (result.first)1132result.first = Builder.CreateFPExt(result.first, ComplexElementTy, "ext");1133if (result.second)1134result.second = Builder.CreateFPExt(result.second, ComplexElementTy, "ext");11351136return result;1137}11381139ComplexPairTy ComplexExprEmitter::EmitPromoted(const Expr *E,1140QualType PromotionType) {1141E = E->IgnoreParens();1142if (auto BO = dyn_cast<BinaryOperator>(E)) {1143switch (BO->getOpcode()) {1144#define HANDLE_BINOP(OP) \1145case BO_##OP: \1146return EmitBin##OP(EmitBinOps(BO, PromotionType));1147HANDLE_BINOP(Add)1148HANDLE_BINOP(Sub)1149HANDLE_BINOP(Mul)1150HANDLE_BINOP(Div)1151#undef HANDLE_BINOP1152default:1153break;1154}1155} else if (auto UO = dyn_cast<UnaryOperator>(E)) {1156switch (UO->getOpcode()) {1157case UO_Minus:1158return VisitMinus(UO, PromotionType);1159case UO_Plus:1160return VisitPlus(UO, PromotionType);1161default:1162break;1163}1164}1165auto result = Visit(const_cast<Expr *>(E));1166if (!PromotionType.isNull())1167return CGF.EmitPromotedValue(result, PromotionType);1168else1169return result;1170}11711172ComplexPairTy CodeGenFunction::EmitPromotedComplexExpr(const Expr *E,1173QualType DstTy) {1174return ComplexExprEmitter(*this).EmitPromoted(E, DstTy);1175}11761177ComplexPairTy1178ComplexExprEmitter::EmitPromotedComplexOperand(const Expr *E,1179QualType OverallPromotionType) {1180if (E->getType()->isAnyComplexType()) {1181if (!OverallPromotionType.isNull())1182return CGF.EmitPromotedComplexExpr(E, OverallPromotionType);1183else1184return Visit(const_cast<Expr *>(E));1185} else {1186if (!OverallPromotionType.isNull()) {1187QualType ComplexElementTy =1188OverallPromotionType->castAs<ComplexType>()->getElementType();1189return ComplexPairTy(CGF.EmitPromotedScalarExpr(E, ComplexElementTy),1190nullptr);1191} else {1192return ComplexPairTy(CGF.EmitScalarExpr(E), nullptr);1193}1194}1195}11961197ComplexExprEmitter::BinOpInfo1198ComplexExprEmitter::EmitBinOps(const BinaryOperator *E,1199QualType PromotionType) {1200TestAndClearIgnoreReal();1201TestAndClearIgnoreImag();1202BinOpInfo Ops;12031204Ops.LHS = EmitPromotedComplexOperand(E->getLHS(), PromotionType);1205Ops.RHS = EmitPromotedComplexOperand(E->getRHS(), PromotionType);1206if (!PromotionType.isNull())1207Ops.Ty = PromotionType;1208else1209Ops.Ty = E->getType();1210Ops.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());1211return Ops;1212}121312141215LValue ComplexExprEmitter::1216EmitCompoundAssignLValue(const CompoundAssignOperator *E,1217ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo&),1218RValue &Val) {1219TestAndClearIgnoreReal();1220TestAndClearIgnoreImag();1221QualType LHSTy = E->getLHS()->getType();1222if (const AtomicType *AT = LHSTy->getAs<AtomicType>())1223LHSTy = AT->getValueType();12241225BinOpInfo OpInfo;1226OpInfo.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());1227CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, OpInfo.FPFeatures);12281229// Load the RHS and LHS operands.1230// __block variables need to have the rhs evaluated first, plus this should1231// improve codegen a little.1232QualType PromotionTypeCR;1233PromotionTypeCR = getPromotionType(E->getStoredFPFeaturesOrDefault(),1234E->getComputationResultType());1235if (PromotionTypeCR.isNull())1236PromotionTypeCR = E->getComputationResultType();1237OpInfo.Ty = PromotionTypeCR;1238QualType ComplexElementTy =1239OpInfo.Ty->castAs<ComplexType>()->getElementType();1240QualType PromotionTypeRHS = getPromotionType(1241E->getStoredFPFeaturesOrDefault(), E->getRHS()->getType());12421243// The RHS should have been converted to the computation type.1244if (E->getRHS()->getType()->isRealFloatingType()) {1245if (!PromotionTypeRHS.isNull())1246OpInfo.RHS = ComplexPairTy(1247CGF.EmitPromotedScalarExpr(E->getRHS(), PromotionTypeRHS), nullptr);1248else {1249assert(CGF.getContext().hasSameUnqualifiedType(ComplexElementTy,1250E->getRHS()->getType()));12511252OpInfo.RHS = ComplexPairTy(CGF.EmitScalarExpr(E->getRHS()), nullptr);1253}1254} else {1255if (!PromotionTypeRHS.isNull()) {1256OpInfo.RHS = ComplexPairTy(1257CGF.EmitPromotedComplexExpr(E->getRHS(), PromotionTypeRHS));1258} else {1259assert(CGF.getContext().hasSameUnqualifiedType(OpInfo.Ty,1260E->getRHS()->getType()));1261OpInfo.RHS = Visit(E->getRHS());1262}1263}12641265LValue LHS = CGF.EmitLValue(E->getLHS());12661267// Load from the l-value and convert it.1268SourceLocation Loc = E->getExprLoc();1269QualType PromotionTypeLHS = getPromotionType(1270E->getStoredFPFeaturesOrDefault(), E->getComputationLHSType());1271if (LHSTy->isAnyComplexType()) {1272ComplexPairTy LHSVal = EmitLoadOfLValue(LHS, Loc);1273if (!PromotionTypeLHS.isNull())1274OpInfo.LHS =1275EmitComplexToComplexCast(LHSVal, LHSTy, PromotionTypeLHS, Loc);1276else1277OpInfo.LHS = EmitComplexToComplexCast(LHSVal, LHSTy, OpInfo.Ty, Loc);1278} else {1279llvm::Value *LHSVal = CGF.EmitLoadOfScalar(LHS, Loc);1280// For floating point real operands we can directly pass the scalar form1281// to the binary operator emission and potentially get more efficient code.1282if (LHSTy->isRealFloatingType()) {1283QualType PromotedComplexElementTy;1284if (!PromotionTypeLHS.isNull()) {1285PromotedComplexElementTy =1286cast<ComplexType>(PromotionTypeLHS)->getElementType();1287if (!CGF.getContext().hasSameUnqualifiedType(PromotedComplexElementTy,1288PromotionTypeLHS))1289LHSVal = CGF.EmitScalarConversion(LHSVal, LHSTy,1290PromotedComplexElementTy, Loc);1291} else {1292if (!CGF.getContext().hasSameUnqualifiedType(ComplexElementTy, LHSTy))1293LHSVal =1294CGF.EmitScalarConversion(LHSVal, LHSTy, ComplexElementTy, Loc);1295}1296OpInfo.LHS = ComplexPairTy(LHSVal, nullptr);1297} else {1298OpInfo.LHS = EmitScalarToComplexCast(LHSVal, LHSTy, OpInfo.Ty, Loc);1299}1300}13011302// Expand the binary operator.1303ComplexPairTy Result = (this->*Func)(OpInfo);13041305// Truncate the result and store it into the LHS lvalue.1306if (LHSTy->isAnyComplexType()) {1307ComplexPairTy ResVal =1308EmitComplexToComplexCast(Result, OpInfo.Ty, LHSTy, Loc);1309EmitStoreOfComplex(ResVal, LHS, /*isInit*/ false);1310Val = RValue::getComplex(ResVal);1311} else {1312llvm::Value *ResVal =1313CGF.EmitComplexToScalarConversion(Result, OpInfo.Ty, LHSTy, Loc);1314CGF.EmitStoreOfScalar(ResVal, LHS, /*isInit*/ false);1315Val = RValue::get(ResVal);1316}13171318return LHS;1319}13201321// Compound assignments.1322ComplexPairTy ComplexExprEmitter::1323EmitCompoundAssign(const CompoundAssignOperator *E,1324ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo&)){1325RValue Val;1326LValue LV = EmitCompoundAssignLValue(E, Func, Val);13271328// The result of an assignment in C is the assigned r-value.1329if (!CGF.getLangOpts().CPlusPlus)1330return Val.getComplexVal();13311332// If the lvalue is non-volatile, return the computed value of the assignment.1333if (!LV.isVolatileQualified())1334return Val.getComplexVal();13351336return EmitLoadOfLValue(LV, E->getExprLoc());1337}13381339LValue ComplexExprEmitter::EmitBinAssignLValue(const BinaryOperator *E,1340ComplexPairTy &Val) {1341assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),1342E->getRHS()->getType()) &&1343"Invalid assignment");1344TestAndClearIgnoreReal();1345TestAndClearIgnoreImag();13461347// Emit the RHS. __block variables need the RHS evaluated first.1348Val = Visit(E->getRHS());13491350// Compute the address to store into.1351LValue LHS = CGF.EmitLValue(E->getLHS());13521353// Store the result value into the LHS lvalue.1354EmitStoreOfComplex(Val, LHS, /*isInit*/ false);13551356return LHS;1357}13581359ComplexPairTy ComplexExprEmitter::VisitBinAssign(const BinaryOperator *E) {1360ComplexPairTy Val;1361LValue LV = EmitBinAssignLValue(E, Val);13621363// The result of an assignment in C is the assigned r-value.1364if (!CGF.getLangOpts().CPlusPlus)1365return Val;13661367// If the lvalue is non-volatile, return the computed value of the assignment.1368if (!LV.isVolatileQualified())1369return Val;13701371return EmitLoadOfLValue(LV, E->getExprLoc());1372}13731374ComplexPairTy ComplexExprEmitter::VisitBinComma(const BinaryOperator *E) {1375CGF.EmitIgnoredExpr(E->getLHS());1376return Visit(E->getRHS());1377}13781379ComplexPairTy ComplexExprEmitter::1380VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {1381TestAndClearIgnoreReal();1382TestAndClearIgnoreImag();1383llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");1384llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");1385llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");13861387// Bind the common expression if necessary.1388CodeGenFunction::OpaqueValueMapping binding(CGF, E);138913901391CodeGenFunction::ConditionalEvaluation eval(CGF);1392CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,1393CGF.getProfileCount(E));13941395eval.begin(CGF);1396CGF.EmitBlock(LHSBlock);1397if (llvm::EnableSingleByteCoverage)1398CGF.incrementProfileCounter(E->getTrueExpr());1399else1400CGF.incrementProfileCounter(E);14011402ComplexPairTy LHS = Visit(E->getTrueExpr());1403LHSBlock = Builder.GetInsertBlock();1404CGF.EmitBranch(ContBlock);1405eval.end(CGF);14061407eval.begin(CGF);1408CGF.EmitBlock(RHSBlock);1409if (llvm::EnableSingleByteCoverage)1410CGF.incrementProfileCounter(E->getFalseExpr());1411ComplexPairTy RHS = Visit(E->getFalseExpr());1412RHSBlock = Builder.GetInsertBlock();1413CGF.EmitBlock(ContBlock);1414if (llvm::EnableSingleByteCoverage)1415CGF.incrementProfileCounter(E);1416eval.end(CGF);14171418// Create a PHI node for the real part.1419llvm::PHINode *RealPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.r");1420RealPN->addIncoming(LHS.first, LHSBlock);1421RealPN->addIncoming(RHS.first, RHSBlock);14221423// Create a PHI node for the imaginary part.1424llvm::PHINode *ImagPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.i");1425ImagPN->addIncoming(LHS.second, LHSBlock);1426ImagPN->addIncoming(RHS.second, RHSBlock);14271428return ComplexPairTy(RealPN, ImagPN);1429}14301431ComplexPairTy ComplexExprEmitter::VisitChooseExpr(ChooseExpr *E) {1432return Visit(E->getChosenSubExpr());1433}14341435ComplexPairTy ComplexExprEmitter::VisitInitListExpr(InitListExpr *E) {1436bool Ignore = TestAndClearIgnoreReal();1437(void)Ignore;1438assert (Ignore == false && "init list ignored");1439Ignore = TestAndClearIgnoreImag();1440(void)Ignore;1441assert (Ignore == false && "init list ignored");14421443if (E->getNumInits() == 2) {1444llvm::Value *Real = CGF.EmitScalarExpr(E->getInit(0));1445llvm::Value *Imag = CGF.EmitScalarExpr(E->getInit(1));1446return ComplexPairTy(Real, Imag);1447} else if (E->getNumInits() == 1) {1448return Visit(E->getInit(0));1449}14501451// Empty init list initializes to null1452assert(E->getNumInits() == 0 && "Unexpected number of inits");1453QualType Ty = E->getType()->castAs<ComplexType>()->getElementType();1454llvm::Type* LTy = CGF.ConvertType(Ty);1455llvm::Value* zeroConstant = llvm::Constant::getNullValue(LTy);1456return ComplexPairTy(zeroConstant, zeroConstant);1457}14581459ComplexPairTy ComplexExprEmitter::VisitVAArgExpr(VAArgExpr *E) {1460Address ArgValue = Address::invalid();1461RValue RV = CGF.EmitVAArg(E, ArgValue);14621463if (!ArgValue.isValid()) {1464CGF.ErrorUnsupported(E, "complex va_arg expression");1465llvm::Type *EltTy =1466CGF.ConvertType(E->getType()->castAs<ComplexType>()->getElementType());1467llvm::Value *U = llvm::UndefValue::get(EltTy);1468return ComplexPairTy(U, U);1469}14701471return RV.getComplexVal();1472}14731474//===----------------------------------------------------------------------===//1475// Entry Point into this File1476//===----------------------------------------------------------------------===//14771478/// EmitComplexExpr - Emit the computation of the specified expression of1479/// complex type, ignoring the result.1480ComplexPairTy CodeGenFunction::EmitComplexExpr(const Expr *E, bool IgnoreReal,1481bool IgnoreImag) {1482assert(E && getComplexType(E->getType()) &&1483"Invalid complex expression to emit");14841485return ComplexExprEmitter(*this, IgnoreReal, IgnoreImag)1486.Visit(const_cast<Expr *>(E));1487}14881489void CodeGenFunction::EmitComplexExprIntoLValue(const Expr *E, LValue dest,1490bool isInit) {1491assert(E && getComplexType(E->getType()) &&1492"Invalid complex expression to emit");1493ComplexExprEmitter Emitter(*this);1494ComplexPairTy Val = Emitter.Visit(const_cast<Expr*>(E));1495Emitter.EmitStoreOfComplex(Val, dest, isInit);1496}14971498/// EmitStoreOfComplex - Store a complex number into the specified l-value.1499void CodeGenFunction::EmitStoreOfComplex(ComplexPairTy V, LValue dest,1500bool isInit) {1501ComplexExprEmitter(*this).EmitStoreOfComplex(V, dest, isInit);1502}15031504/// EmitLoadOfComplex - Load a complex number from the specified address.1505ComplexPairTy CodeGenFunction::EmitLoadOfComplex(LValue src,1506SourceLocation loc) {1507return ComplexExprEmitter(*this).EmitLoadOfLValue(src, loc);1508}15091510LValue CodeGenFunction::EmitComplexAssignmentLValue(const BinaryOperator *E) {1511assert(E->getOpcode() == BO_Assign);1512ComplexPairTy Val; // ignored1513LValue LVal = ComplexExprEmitter(*this).EmitBinAssignLValue(E, Val);1514if (getLangOpts().OpenMP)1515CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,1516E->getLHS());1517return LVal;1518}15191520typedef ComplexPairTy (ComplexExprEmitter::*CompoundFunc)(1521const ComplexExprEmitter::BinOpInfo &);15221523static CompoundFunc getComplexOp(BinaryOperatorKind Op) {1524switch (Op) {1525case BO_MulAssign: return &ComplexExprEmitter::EmitBinMul;1526case BO_DivAssign: return &ComplexExprEmitter::EmitBinDiv;1527case BO_SubAssign: return &ComplexExprEmitter::EmitBinSub;1528case BO_AddAssign: return &ComplexExprEmitter::EmitBinAdd;1529default:1530llvm_unreachable("unexpected complex compound assignment");1531}1532}15331534LValue CodeGenFunction::1535EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E) {1536CompoundFunc Op = getComplexOp(E->getOpcode());1537RValue Val;1538return ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);1539}15401541LValue CodeGenFunction::1542EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,1543llvm::Value *&Result) {1544CompoundFunc Op = getComplexOp(E->getOpcode());1545RValue Val;1546LValue Ret = ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);1547Result = Val.getScalarVal();1548return Ret;1549}155015511552