[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / clang / lib / CodeGen / CGExprComplex.cpp
blobf3cbd1d0451ebe4f8d15b24306fb685d763430d2
1 //===--- CGExprComplex.cpp - Emit LLVM Code for Complex Exprs -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code to emit Expr nodes with complex types as LLVM code.
11 //===----------------------------------------------------------------------===//
13 #include "CGOpenMPRuntime.h"
14 #include "CodeGenFunction.h"
15 #include "CodeGenModule.h"
16 #include "ConstantEmitter.h"
17 #include "clang/AST/StmtVisitor.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/Instructions.h"
21 #include "llvm/IR/MDBuilder.h"
22 #include "llvm/IR/Metadata.h"
23 #include <algorithm>
24 using namespace clang;
25 using namespace CodeGen;
27 //===----------------------------------------------------------------------===//
28 // Complex Expression Emitter
29 //===----------------------------------------------------------------------===//
31 typedef CodeGenFunction::ComplexPairTy ComplexPairTy;
33 /// Return the complex type that we are meant to emit.
34 static const ComplexType *getComplexType(QualType type) {
35 type = type.getCanonicalType();
36 if (const ComplexType *comp = dyn_cast<ComplexType>(type)) {
37 return comp;
38 } else {
39 return cast<ComplexType>(cast<AtomicType>(type)->getValueType());
43 namespace {
44 class ComplexExprEmitter
45 : public StmtVisitor<ComplexExprEmitter, ComplexPairTy> {
46 CodeGenFunction &CGF;
47 CGBuilderTy &Builder;
48 bool IgnoreReal;
49 bool IgnoreImag;
50 public:
51 ComplexExprEmitter(CodeGenFunction &cgf, bool ir=false, bool ii=false)
52 : CGF(cgf), Builder(CGF.Builder), IgnoreReal(ir), IgnoreImag(ii) {
56 //===--------------------------------------------------------------------===//
57 // Utilities
58 //===--------------------------------------------------------------------===//
60 bool TestAndClearIgnoreReal() {
61 bool I = IgnoreReal;
62 IgnoreReal = false;
63 return I;
65 bool TestAndClearIgnoreImag() {
66 bool I = IgnoreImag;
67 IgnoreImag = false;
68 return I;
71 /// EmitLoadOfLValue - Given an expression with complex type that represents a
72 /// value l-value, this method emits the address of the l-value, then loads
73 /// and returns the result.
74 ComplexPairTy EmitLoadOfLValue(const Expr *E) {
75 return EmitLoadOfLValue(CGF.EmitLValue(E), E->getExprLoc());
78 ComplexPairTy EmitLoadOfLValue(LValue LV, SourceLocation Loc);
80 /// EmitStoreOfComplex - Store the specified real/imag parts into the
81 /// specified value pointer.
82 void EmitStoreOfComplex(ComplexPairTy Val, LValue LV, bool isInit);
84 /// Emit a cast from complex value Val to DestType.
85 ComplexPairTy EmitComplexToComplexCast(ComplexPairTy Val, QualType SrcType,
86 QualType DestType, SourceLocation Loc);
87 /// Emit a cast from scalar value Val to DestType.
88 ComplexPairTy EmitScalarToComplexCast(llvm::Value *Val, QualType SrcType,
89 QualType DestType, SourceLocation Loc);
91 //===--------------------------------------------------------------------===//
92 // Visitor Methods
93 //===--------------------------------------------------------------------===//
95 ComplexPairTy Visit(Expr *E) {
96 ApplyDebugLocation DL(CGF, E);
97 return StmtVisitor<ComplexExprEmitter, ComplexPairTy>::Visit(E);
100 ComplexPairTy VisitStmt(Stmt *S) {
101 S->dump(llvm::errs(), CGF.getContext());
102 llvm_unreachable("Stmt can't have complex result type!");
104 ComplexPairTy VisitExpr(Expr *S);
105 ComplexPairTy VisitConstantExpr(ConstantExpr *E) {
106 if (llvm::Constant *Result = ConstantEmitter(CGF).tryEmitConstantExpr(E))
107 return ComplexPairTy(Result->getAggregateElement(0U),
108 Result->getAggregateElement(1U));
109 return Visit(E->getSubExpr());
111 ComplexPairTy VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr());}
112 ComplexPairTy VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
113 return Visit(GE->getResultExpr());
115 ComplexPairTy VisitImaginaryLiteral(const ImaginaryLiteral *IL);
116 ComplexPairTy
117 VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE) {
118 return Visit(PE->getReplacement());
120 ComplexPairTy VisitCoawaitExpr(CoawaitExpr *S) {
121 return CGF.EmitCoawaitExpr(*S).getComplexVal();
123 ComplexPairTy VisitCoyieldExpr(CoyieldExpr *S) {
124 return CGF.EmitCoyieldExpr(*S).getComplexVal();
126 ComplexPairTy VisitUnaryCoawait(const UnaryOperator *E) {
127 return Visit(E->getSubExpr());
130 ComplexPairTy emitConstant(const CodeGenFunction::ConstantEmission &Constant,
131 Expr *E) {
132 assert(Constant && "not a constant");
133 if (Constant.isReference())
134 return EmitLoadOfLValue(Constant.getReferenceLValue(CGF, E),
135 E->getExprLoc());
137 llvm::Constant *pair = Constant.getValue();
138 return ComplexPairTy(pair->getAggregateElement(0U),
139 pair->getAggregateElement(1U));
142 // l-values.
143 ComplexPairTy VisitDeclRefExpr(DeclRefExpr *E) {
144 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E))
145 return emitConstant(Constant, E);
146 return EmitLoadOfLValue(E);
148 ComplexPairTy VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
149 return EmitLoadOfLValue(E);
151 ComplexPairTy VisitObjCMessageExpr(ObjCMessageExpr *E) {
152 return CGF.EmitObjCMessageExpr(E).getComplexVal();
154 ComplexPairTy VisitArraySubscriptExpr(Expr *E) { return EmitLoadOfLValue(E); }
155 ComplexPairTy VisitMemberExpr(MemberExpr *ME) {
156 if (CodeGenFunction::ConstantEmission Constant =
157 CGF.tryEmitAsConstant(ME)) {
158 CGF.EmitIgnoredExpr(ME->getBase());
159 return emitConstant(Constant, ME);
161 return EmitLoadOfLValue(ME);
163 ComplexPairTy VisitOpaqueValueExpr(OpaqueValueExpr *E) {
164 if (E->isGLValue())
165 return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E),
166 E->getExprLoc());
167 return CGF.getOrCreateOpaqueRValueMapping(E).getComplexVal();
170 ComplexPairTy VisitPseudoObjectExpr(PseudoObjectExpr *E) {
171 return CGF.EmitPseudoObjectRValue(E).getComplexVal();
174 // FIXME: CompoundLiteralExpr
176 ComplexPairTy EmitCast(CastKind CK, Expr *Op, QualType DestTy);
177 ComplexPairTy VisitImplicitCastExpr(ImplicitCastExpr *E) {
178 // Unlike for scalars, we don't have to worry about function->ptr demotion
179 // here.
180 if (E->changesVolatileQualification())
181 return EmitLoadOfLValue(E);
182 return EmitCast(E->getCastKind(), E->getSubExpr(), E->getType());
184 ComplexPairTy VisitCastExpr(CastExpr *E) {
185 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
186 CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
187 if (E->changesVolatileQualification())
188 return EmitLoadOfLValue(E);
189 return EmitCast(E->getCastKind(), E->getSubExpr(), E->getType());
191 ComplexPairTy VisitCallExpr(const CallExpr *E);
192 ComplexPairTy VisitStmtExpr(const StmtExpr *E);
194 // Operators.
195 ComplexPairTy VisitPrePostIncDec(const UnaryOperator *E,
196 bool isInc, bool isPre) {
197 LValue LV = CGF.EmitLValue(E->getSubExpr());
198 return CGF.EmitComplexPrePostIncDec(E, LV, isInc, isPre);
200 ComplexPairTy VisitUnaryPostDec(const UnaryOperator *E) {
201 return VisitPrePostIncDec(E, false, false);
203 ComplexPairTy VisitUnaryPostInc(const UnaryOperator *E) {
204 return VisitPrePostIncDec(E, true, false);
206 ComplexPairTy VisitUnaryPreDec(const UnaryOperator *E) {
207 return VisitPrePostIncDec(E, false, true);
209 ComplexPairTy VisitUnaryPreInc(const UnaryOperator *E) {
210 return VisitPrePostIncDec(E, true, true);
212 ComplexPairTy VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
214 ComplexPairTy VisitUnaryPlus(const UnaryOperator *E,
215 QualType PromotionType = QualType());
216 ComplexPairTy VisitPlus(const UnaryOperator *E, QualType PromotionType);
217 ComplexPairTy VisitUnaryMinus(const UnaryOperator *E,
218 QualType PromotionType = QualType());
219 ComplexPairTy VisitMinus(const UnaryOperator *E, QualType PromotionType);
220 ComplexPairTy VisitUnaryNot (const UnaryOperator *E);
221 // LNot,Real,Imag never return complex.
222 ComplexPairTy VisitUnaryExtension(const UnaryOperator *E) {
223 return Visit(E->getSubExpr());
225 ComplexPairTy VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
226 CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
227 return Visit(DAE->getExpr());
229 ComplexPairTy VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
230 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
231 return Visit(DIE->getExpr());
233 ComplexPairTy VisitExprWithCleanups(ExprWithCleanups *E) {
234 CodeGenFunction::RunCleanupsScope Scope(CGF);
235 ComplexPairTy Vals = Visit(E->getSubExpr());
236 // Defend against dominance problems caused by jumps out of expression
237 // evaluation through the shared cleanup block.
238 Scope.ForceCleanup({&Vals.first, &Vals.second});
239 return Vals;
241 ComplexPairTy VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
242 assert(E->getType()->isAnyComplexType() && "Expected complex type!");
243 QualType Elem = E->getType()->castAs<ComplexType>()->getElementType();
244 llvm::Constant *Null = llvm::Constant::getNullValue(CGF.ConvertType(Elem));
245 return ComplexPairTy(Null, Null);
247 ComplexPairTy VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
248 assert(E->getType()->isAnyComplexType() && "Expected complex type!");
249 QualType Elem = E->getType()->castAs<ComplexType>()->getElementType();
250 llvm::Constant *Null =
251 llvm::Constant::getNullValue(CGF.ConvertType(Elem));
252 return ComplexPairTy(Null, Null);
255 struct BinOpInfo {
256 ComplexPairTy LHS;
257 ComplexPairTy RHS;
258 QualType Ty; // Computation Type.
259 FPOptions FPFeatures;
262 BinOpInfo EmitBinOps(const BinaryOperator *E,
263 QualType PromotionTy = QualType());
264 ComplexPairTy EmitPromoted(const Expr *E, QualType PromotionTy);
265 ComplexPairTy EmitPromotedComplexOperand(const Expr *E, QualType PromotionTy);
266 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
267 ComplexPairTy (ComplexExprEmitter::*Func)
268 (const BinOpInfo &),
269 RValue &Val);
270 ComplexPairTy EmitCompoundAssign(const CompoundAssignOperator *E,
271 ComplexPairTy (ComplexExprEmitter::*Func)
272 (const BinOpInfo &));
274 ComplexPairTy EmitBinAdd(const BinOpInfo &Op);
275 ComplexPairTy EmitBinSub(const BinOpInfo &Op);
276 ComplexPairTy EmitBinMul(const BinOpInfo &Op);
277 ComplexPairTy EmitBinDiv(const BinOpInfo &Op);
279 ComplexPairTy EmitComplexBinOpLibCall(StringRef LibCallName,
280 const BinOpInfo &Op);
282 QualType getPromotionType(QualType Ty) {
283 if (auto *CT = Ty->getAs<ComplexType>()) {
284 QualType ElementType = CT->getElementType();
285 if (ElementType.UseExcessPrecision(CGF.getContext()))
286 return CGF.getContext().getComplexType(CGF.getContext().FloatTy);
288 if (Ty.UseExcessPrecision(CGF.getContext()))
289 return CGF.getContext().FloatTy;
290 return QualType();
293 #define HANDLEBINOP(OP) \
294 ComplexPairTy VisitBin##OP(const BinaryOperator *E) { \
295 QualType promotionTy = getPromotionType(E->getType()); \
296 ComplexPairTy result = EmitBin##OP(EmitBinOps(E, promotionTy)); \
297 if (!promotionTy.isNull()) \
298 result = \
299 CGF.EmitUnPromotedValue(result, E->getType()); \
300 return result; \
303 HANDLEBINOP(Mul)
304 HANDLEBINOP(Div)
305 HANDLEBINOP(Add)
306 HANDLEBINOP(Sub)
307 #undef HANDLEBINOP
309 ComplexPairTy VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
310 return Visit(E->getSemanticForm());
313 // Compound assignments.
314 ComplexPairTy VisitBinAddAssign(const CompoundAssignOperator *E) {
315 return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinAdd);
317 ComplexPairTy VisitBinSubAssign(const CompoundAssignOperator *E) {
318 return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinSub);
320 ComplexPairTy VisitBinMulAssign(const CompoundAssignOperator *E) {
321 return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinMul);
323 ComplexPairTy VisitBinDivAssign(const CompoundAssignOperator *E) {
324 return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinDiv);
327 // GCC rejects rem/and/or/xor for integer complex.
328 // Logical and/or always return int, never complex.
330 // No comparisons produce a complex result.
332 LValue EmitBinAssignLValue(const BinaryOperator *E,
333 ComplexPairTy &Val);
334 ComplexPairTy VisitBinAssign (const BinaryOperator *E);
335 ComplexPairTy VisitBinComma (const BinaryOperator *E);
338 ComplexPairTy
339 VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
340 ComplexPairTy VisitChooseExpr(ChooseExpr *CE);
342 ComplexPairTy VisitInitListExpr(InitListExpr *E);
344 ComplexPairTy VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
345 return EmitLoadOfLValue(E);
348 ComplexPairTy VisitVAArgExpr(VAArgExpr *E);
350 ComplexPairTy VisitAtomicExpr(AtomicExpr *E) {
351 return CGF.EmitAtomicExpr(E).getComplexVal();
354 } // end anonymous namespace.
356 //===----------------------------------------------------------------------===//
357 // Utilities
358 //===----------------------------------------------------------------------===//
360 Address CodeGenFunction::emitAddrOfRealComponent(Address addr,
361 QualType complexType) {
362 return Builder.CreateStructGEP(addr, 0, addr.getName() + ".realp");
365 Address CodeGenFunction::emitAddrOfImagComponent(Address addr,
366 QualType complexType) {
367 return Builder.CreateStructGEP(addr, 1, addr.getName() + ".imagp");
370 /// EmitLoadOfLValue - Given an RValue reference for a complex, emit code to
371 /// load the real and imaginary pieces, returning them as Real/Imag.
372 ComplexPairTy ComplexExprEmitter::EmitLoadOfLValue(LValue lvalue,
373 SourceLocation loc) {
374 assert(lvalue.isSimple() && "non-simple complex l-value?");
375 if (lvalue.getType()->isAtomicType())
376 return CGF.EmitAtomicLoad(lvalue, loc).getComplexVal();
378 Address SrcPtr = lvalue.getAddress(CGF);
379 bool isVolatile = lvalue.isVolatileQualified();
381 llvm::Value *Real = nullptr, *Imag = nullptr;
383 if (!IgnoreReal || isVolatile) {
384 Address RealP = CGF.emitAddrOfRealComponent(SrcPtr, lvalue.getType());
385 Real = Builder.CreateLoad(RealP, isVolatile, SrcPtr.getName() + ".real");
388 if (!IgnoreImag || isVolatile) {
389 Address ImagP = CGF.emitAddrOfImagComponent(SrcPtr, lvalue.getType());
390 Imag = Builder.CreateLoad(ImagP, isVolatile, SrcPtr.getName() + ".imag");
393 return ComplexPairTy(Real, Imag);
396 /// EmitStoreOfComplex - Store the specified real/imag parts into the
397 /// specified value pointer.
398 void ComplexExprEmitter::EmitStoreOfComplex(ComplexPairTy Val, LValue lvalue,
399 bool isInit) {
400 if (lvalue.getType()->isAtomicType() ||
401 (!isInit && CGF.LValueIsSuitableForInlineAtomic(lvalue)))
402 return CGF.EmitAtomicStore(RValue::getComplex(Val), lvalue, isInit);
404 Address Ptr = lvalue.getAddress(CGF);
405 Address RealPtr = CGF.emitAddrOfRealComponent(Ptr, lvalue.getType());
406 Address ImagPtr = CGF.emitAddrOfImagComponent(Ptr, lvalue.getType());
408 Builder.CreateStore(Val.first, RealPtr, lvalue.isVolatileQualified());
409 Builder.CreateStore(Val.second, ImagPtr, lvalue.isVolatileQualified());
414 //===----------------------------------------------------------------------===//
415 // Visitor Methods
416 //===----------------------------------------------------------------------===//
418 ComplexPairTy ComplexExprEmitter::VisitExpr(Expr *E) {
419 CGF.ErrorUnsupported(E, "complex expression");
420 llvm::Type *EltTy =
421 CGF.ConvertType(getComplexType(E->getType())->getElementType());
422 llvm::Value *U = llvm::UndefValue::get(EltTy);
423 return ComplexPairTy(U, U);
426 ComplexPairTy ComplexExprEmitter::
427 VisitImaginaryLiteral(const ImaginaryLiteral *IL) {
428 llvm::Value *Imag = CGF.EmitScalarExpr(IL->getSubExpr());
429 return ComplexPairTy(llvm::Constant::getNullValue(Imag->getType()), Imag);
433 ComplexPairTy ComplexExprEmitter::VisitCallExpr(const CallExpr *E) {
434 if (E->getCallReturnType(CGF.getContext())->isReferenceType())
435 return EmitLoadOfLValue(E);
437 return CGF.EmitCallExpr(E).getComplexVal();
440 ComplexPairTy ComplexExprEmitter::VisitStmtExpr(const StmtExpr *E) {
441 CodeGenFunction::StmtExprEvaluation eval(CGF);
442 Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(), true);
443 assert(RetAlloca.isValid() && "Expected complex return value");
444 return EmitLoadOfLValue(CGF.MakeAddrLValue(RetAlloca, E->getType()),
445 E->getExprLoc());
448 /// Emit a cast from complex value Val to DestType.
449 ComplexPairTy ComplexExprEmitter::EmitComplexToComplexCast(ComplexPairTy Val,
450 QualType SrcType,
451 QualType DestType,
452 SourceLocation Loc) {
453 // Get the src/dest element type.
454 SrcType = SrcType->castAs<ComplexType>()->getElementType();
455 DestType = DestType->castAs<ComplexType>()->getElementType();
457 // C99 6.3.1.6: When a value of complex type is converted to another
458 // complex type, both the real and imaginary parts follow the conversion
459 // rules for the corresponding real types.
460 if (Val.first)
461 Val.first = CGF.EmitScalarConversion(Val.first, SrcType, DestType, Loc);
462 if (Val.second)
463 Val.second = CGF.EmitScalarConversion(Val.second, SrcType, DestType, Loc);
464 return Val;
467 ComplexPairTy ComplexExprEmitter::EmitScalarToComplexCast(llvm::Value *Val,
468 QualType SrcType,
469 QualType DestType,
470 SourceLocation Loc) {
471 // Convert the input element to the element type of the complex.
472 DestType = DestType->castAs<ComplexType>()->getElementType();
473 Val = CGF.EmitScalarConversion(Val, SrcType, DestType, Loc);
475 // Return (realval, 0).
476 return ComplexPairTy(Val, llvm::Constant::getNullValue(Val->getType()));
479 ComplexPairTy ComplexExprEmitter::EmitCast(CastKind CK, Expr *Op,
480 QualType DestTy) {
481 switch (CK) {
482 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
484 // Atomic to non-atomic casts may be more than a no-op for some platforms and
485 // for some types.
486 case CK_AtomicToNonAtomic:
487 case CK_NonAtomicToAtomic:
488 case CK_NoOp:
489 case CK_LValueToRValue:
490 case CK_UserDefinedConversion:
491 return Visit(Op);
493 case CK_LValueBitCast: {
494 LValue origLV = CGF.EmitLValue(Op);
495 Address V = origLV.getAddress(CGF).withElementType(CGF.ConvertType(DestTy));
496 return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy), Op->getExprLoc());
499 case CK_LValueToRValueBitCast: {
500 LValue SourceLVal = CGF.EmitLValue(Op);
501 Address Addr = SourceLVal.getAddress(CGF).withElementType(
502 CGF.ConvertTypeForMem(DestTy));
503 LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
504 DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
505 return EmitLoadOfLValue(DestLV, Op->getExprLoc());
508 case CK_BitCast:
509 case CK_BaseToDerived:
510 case CK_DerivedToBase:
511 case CK_UncheckedDerivedToBase:
512 case CK_Dynamic:
513 case CK_ToUnion:
514 case CK_ArrayToPointerDecay:
515 case CK_FunctionToPointerDecay:
516 case CK_NullToPointer:
517 case CK_NullToMemberPointer:
518 case CK_BaseToDerivedMemberPointer:
519 case CK_DerivedToBaseMemberPointer:
520 case CK_MemberPointerToBoolean:
521 case CK_ReinterpretMemberPointer:
522 case CK_ConstructorConversion:
523 case CK_IntegralToPointer:
524 case CK_PointerToIntegral:
525 case CK_PointerToBoolean:
526 case CK_ToVoid:
527 case CK_VectorSplat:
528 case CK_IntegralCast:
529 case CK_BooleanToSignedIntegral:
530 case CK_IntegralToBoolean:
531 case CK_IntegralToFloating:
532 case CK_FloatingToIntegral:
533 case CK_FloatingToBoolean:
534 case CK_FloatingCast:
535 case CK_CPointerToObjCPointerCast:
536 case CK_BlockPointerToObjCPointerCast:
537 case CK_AnyPointerToBlockPointerCast:
538 case CK_ObjCObjectLValueCast:
539 case CK_FloatingComplexToReal:
540 case CK_FloatingComplexToBoolean:
541 case CK_IntegralComplexToReal:
542 case CK_IntegralComplexToBoolean:
543 case CK_ARCProduceObject:
544 case CK_ARCConsumeObject:
545 case CK_ARCReclaimReturnedObject:
546 case CK_ARCExtendBlockObject:
547 case CK_CopyAndAutoreleaseBlockObject:
548 case CK_BuiltinFnToFnPtr:
549 case CK_ZeroToOCLOpaqueType:
550 case CK_AddressSpaceConversion:
551 case CK_IntToOCLSampler:
552 case CK_FloatingToFixedPoint:
553 case CK_FixedPointToFloating:
554 case CK_FixedPointCast:
555 case CK_FixedPointToBoolean:
556 case CK_FixedPointToIntegral:
557 case CK_IntegralToFixedPoint:
558 case CK_MatrixCast:
559 llvm_unreachable("invalid cast kind for complex value");
561 case CK_FloatingRealToComplex:
562 case CK_IntegralRealToComplex: {
563 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op);
564 return EmitScalarToComplexCast(CGF.EmitScalarExpr(Op), Op->getType(),
565 DestTy, Op->getExprLoc());
568 case CK_FloatingComplexCast:
569 case CK_FloatingComplexToIntegralComplex:
570 case CK_IntegralComplexCast:
571 case CK_IntegralComplexToFloatingComplex: {
572 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op);
573 return EmitComplexToComplexCast(Visit(Op), Op->getType(), DestTy,
574 Op->getExprLoc());
578 llvm_unreachable("unknown cast resulting in complex value");
581 ComplexPairTy ComplexExprEmitter::VisitUnaryPlus(const UnaryOperator *E,
582 QualType PromotionType) {
583 QualType promotionTy = PromotionType.isNull()
584 ? getPromotionType(E->getSubExpr()->getType())
585 : PromotionType;
586 ComplexPairTy result = VisitPlus(E, promotionTy);
587 if (!promotionTy.isNull())
588 return CGF.EmitUnPromotedValue(result, E->getSubExpr()->getType());
589 return result;
592 ComplexPairTy ComplexExprEmitter::VisitPlus(const UnaryOperator *E,
593 QualType PromotionType) {
594 TestAndClearIgnoreReal();
595 TestAndClearIgnoreImag();
596 if (!PromotionType.isNull())
597 return CGF.EmitPromotedComplexExpr(E->getSubExpr(), PromotionType);
598 return Visit(E->getSubExpr());
601 ComplexPairTy ComplexExprEmitter::VisitUnaryMinus(const UnaryOperator *E,
602 QualType PromotionType) {
603 QualType promotionTy = PromotionType.isNull()
604 ? getPromotionType(E->getSubExpr()->getType())
605 : PromotionType;
606 ComplexPairTy result = VisitMinus(E, promotionTy);
607 if (!promotionTy.isNull())
608 return CGF.EmitUnPromotedValue(result, E->getSubExpr()->getType());
609 return result;
611 ComplexPairTy ComplexExprEmitter::VisitMinus(const UnaryOperator *E,
612 QualType PromotionType) {
613 TestAndClearIgnoreReal();
614 TestAndClearIgnoreImag();
615 ComplexPairTy Op;
616 if (!PromotionType.isNull())
617 Op = CGF.EmitPromotedComplexExpr(E->getSubExpr(), PromotionType);
618 else
619 Op = Visit(E->getSubExpr());
621 llvm::Value *ResR, *ResI;
622 if (Op.first->getType()->isFloatingPointTy()) {
623 ResR = Builder.CreateFNeg(Op.first, "neg.r");
624 ResI = Builder.CreateFNeg(Op.second, "neg.i");
625 } else {
626 ResR = Builder.CreateNeg(Op.first, "neg.r");
627 ResI = Builder.CreateNeg(Op.second, "neg.i");
629 return ComplexPairTy(ResR, ResI);
632 ComplexPairTy ComplexExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
633 TestAndClearIgnoreReal();
634 TestAndClearIgnoreImag();
635 // ~(a+ib) = a + i*-b
636 ComplexPairTy Op = Visit(E->getSubExpr());
637 llvm::Value *ResI;
638 if (Op.second->getType()->isFloatingPointTy())
639 ResI = Builder.CreateFNeg(Op.second, "conj.i");
640 else
641 ResI = Builder.CreateNeg(Op.second, "conj.i");
643 return ComplexPairTy(Op.first, ResI);
646 ComplexPairTy ComplexExprEmitter::EmitBinAdd(const BinOpInfo &Op) {
647 llvm::Value *ResR, *ResI;
649 if (Op.LHS.first->getType()->isFloatingPointTy()) {
650 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op.FPFeatures);
651 ResR = Builder.CreateFAdd(Op.LHS.first, Op.RHS.first, "add.r");
652 if (Op.LHS.second && Op.RHS.second)
653 ResI = Builder.CreateFAdd(Op.LHS.second, Op.RHS.second, "add.i");
654 else
655 ResI = Op.LHS.second ? Op.LHS.second : Op.RHS.second;
656 assert(ResI && "Only one operand may be real!");
657 } else {
658 ResR = Builder.CreateAdd(Op.LHS.first, Op.RHS.first, "add.r");
659 assert(Op.LHS.second && Op.RHS.second &&
660 "Both operands of integer complex operators must be complex!");
661 ResI = Builder.CreateAdd(Op.LHS.second, Op.RHS.second, "add.i");
663 return ComplexPairTy(ResR, ResI);
666 ComplexPairTy ComplexExprEmitter::EmitBinSub(const BinOpInfo &Op) {
667 llvm::Value *ResR, *ResI;
668 if (Op.LHS.first->getType()->isFloatingPointTy()) {
669 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op.FPFeatures);
670 ResR = Builder.CreateFSub(Op.LHS.first, Op.RHS.first, "sub.r");
671 if (Op.LHS.second && Op.RHS.second)
672 ResI = Builder.CreateFSub(Op.LHS.second, Op.RHS.second, "sub.i");
673 else
674 ResI = Op.LHS.second ? Op.LHS.second
675 : Builder.CreateFNeg(Op.RHS.second, "sub.i");
676 assert(ResI && "Only one operand may be real!");
677 } else {
678 ResR = Builder.CreateSub(Op.LHS.first, Op.RHS.first, "sub.r");
679 assert(Op.LHS.second && Op.RHS.second &&
680 "Both operands of integer complex operators must be complex!");
681 ResI = Builder.CreateSub(Op.LHS.second, Op.RHS.second, "sub.i");
683 return ComplexPairTy(ResR, ResI);
686 /// Emit a libcall for a binary operation on complex types.
687 ComplexPairTy ComplexExprEmitter::EmitComplexBinOpLibCall(StringRef LibCallName,
688 const BinOpInfo &Op) {
689 CallArgList Args;
690 Args.add(RValue::get(Op.LHS.first),
691 Op.Ty->castAs<ComplexType>()->getElementType());
692 Args.add(RValue::get(Op.LHS.second),
693 Op.Ty->castAs<ComplexType>()->getElementType());
694 Args.add(RValue::get(Op.RHS.first),
695 Op.Ty->castAs<ComplexType>()->getElementType());
696 Args.add(RValue::get(Op.RHS.second),
697 Op.Ty->castAs<ComplexType>()->getElementType());
699 // We *must* use the full CG function call building logic here because the
700 // complex type has special ABI handling. We also should not forget about
701 // special calling convention which may be used for compiler builtins.
703 // We create a function qualified type to state that this call does not have
704 // any exceptions.
705 FunctionProtoType::ExtProtoInfo EPI;
706 EPI = EPI.withExceptionSpec(
707 FunctionProtoType::ExceptionSpecInfo(EST_BasicNoexcept));
708 SmallVector<QualType, 4> ArgsQTys(
709 4, Op.Ty->castAs<ComplexType>()->getElementType());
710 QualType FQTy = CGF.getContext().getFunctionType(Op.Ty, ArgsQTys, EPI);
711 const CGFunctionInfo &FuncInfo = CGF.CGM.getTypes().arrangeFreeFunctionCall(
712 Args, cast<FunctionType>(FQTy.getTypePtr()), false);
714 llvm::FunctionType *FTy = CGF.CGM.getTypes().GetFunctionType(FuncInfo);
715 llvm::FunctionCallee Func = CGF.CGM.CreateRuntimeFunction(
716 FTy, LibCallName, llvm::AttributeList(), true);
717 CGCallee Callee = CGCallee::forDirect(Func, FQTy->getAs<FunctionProtoType>());
719 llvm::CallBase *Call;
720 RValue Res = CGF.EmitCall(FuncInfo, Callee, ReturnValueSlot(), Args, &Call);
721 Call->setCallingConv(CGF.CGM.getRuntimeCC());
722 return Res.getComplexVal();
725 /// Lookup the libcall name for a given floating point type complex
726 /// multiply.
727 static StringRef getComplexMultiplyLibCallName(llvm::Type *Ty) {
728 switch (Ty->getTypeID()) {
729 default:
730 llvm_unreachable("Unsupported floating point type!");
731 case llvm::Type::HalfTyID:
732 return "__mulhc3";
733 case llvm::Type::FloatTyID:
734 return "__mulsc3";
735 case llvm::Type::DoubleTyID:
736 return "__muldc3";
737 case llvm::Type::PPC_FP128TyID:
738 return "__multc3";
739 case llvm::Type::X86_FP80TyID:
740 return "__mulxc3";
741 case llvm::Type::FP128TyID:
742 return "__multc3";
746 // See C11 Annex G.5.1 for the semantics of multiplicative operators on complex
747 // typed values.
748 ComplexPairTy ComplexExprEmitter::EmitBinMul(const BinOpInfo &Op) {
749 using llvm::Value;
750 Value *ResR, *ResI;
751 llvm::MDBuilder MDHelper(CGF.getLLVMContext());
753 if (Op.LHS.first->getType()->isFloatingPointTy()) {
754 // The general formulation is:
755 // (a + ib) * (c + id) = (a * c - b * d) + i(a * d + b * c)
757 // But we can fold away components which would be zero due to a real
758 // operand according to C11 Annex G.5.1p2.
759 // FIXME: C11 also provides for imaginary types which would allow folding
760 // still more of this within the type system.
762 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op.FPFeatures);
763 if (Op.LHS.second && Op.RHS.second) {
764 // If both operands are complex, emit the core math directly, and then
765 // test for NaNs. If we find NaNs in the result, we delegate to a libcall
766 // to carefully re-compute the correct infinity representation if
767 // possible. The expectation is that the presence of NaNs here is
768 // *extremely* rare, and so the cost of the libcall is almost irrelevant.
769 // This is good, because the libcall re-computes the core multiplication
770 // exactly the same as we do here and re-tests for NaNs in order to be
771 // a generic complex*complex libcall.
773 // First compute the four products.
774 Value *AC = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul_ac");
775 Value *BD = Builder.CreateFMul(Op.LHS.second, Op.RHS.second, "mul_bd");
776 Value *AD = Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul_ad");
777 Value *BC = Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul_bc");
779 // The real part is the difference of the first two, the imaginary part is
780 // the sum of the second.
781 ResR = Builder.CreateFSub(AC, BD, "mul_r");
782 ResI = Builder.CreateFAdd(AD, BC, "mul_i");
784 // Emit the test for the real part becoming NaN and create a branch to
785 // handle it. We test for NaN by comparing the number to itself.
786 Value *IsRNaN = Builder.CreateFCmpUNO(ResR, ResR, "isnan_cmp");
787 llvm::BasicBlock *ContBB = CGF.createBasicBlock("complex_mul_cont");
788 llvm::BasicBlock *INaNBB = CGF.createBasicBlock("complex_mul_imag_nan");
789 llvm::Instruction *Branch = Builder.CreateCondBr(IsRNaN, INaNBB, ContBB);
790 llvm::BasicBlock *OrigBB = Branch->getParent();
792 // Give hint that we very much don't expect to see NaNs.
793 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
794 llvm::MDNode *BrWeight = MDHelper.createBranchWeights(1, (1U << 20) - 1);
795 Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);
797 // Now test the imaginary part and create its branch.
798 CGF.EmitBlock(INaNBB);
799 Value *IsINaN = Builder.CreateFCmpUNO(ResI, ResI, "isnan_cmp");
800 llvm::BasicBlock *LibCallBB = CGF.createBasicBlock("complex_mul_libcall");
801 Branch = Builder.CreateCondBr(IsINaN, LibCallBB, ContBB);
802 Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);
804 // Now emit the libcall on this slowest of the slow paths.
805 CGF.EmitBlock(LibCallBB);
806 Value *LibCallR, *LibCallI;
807 std::tie(LibCallR, LibCallI) = EmitComplexBinOpLibCall(
808 getComplexMultiplyLibCallName(Op.LHS.first->getType()), Op);
809 Builder.CreateBr(ContBB);
811 // Finally continue execution by phi-ing together the different
812 // computation paths.
813 CGF.EmitBlock(ContBB);
814 llvm::PHINode *RealPHI = Builder.CreatePHI(ResR->getType(), 3, "real_mul_phi");
815 RealPHI->addIncoming(ResR, OrigBB);
816 RealPHI->addIncoming(ResR, INaNBB);
817 RealPHI->addIncoming(LibCallR, LibCallBB);
818 llvm::PHINode *ImagPHI = Builder.CreatePHI(ResI->getType(), 3, "imag_mul_phi");
819 ImagPHI->addIncoming(ResI, OrigBB);
820 ImagPHI->addIncoming(ResI, INaNBB);
821 ImagPHI->addIncoming(LibCallI, LibCallBB);
822 return ComplexPairTy(RealPHI, ImagPHI);
824 assert((Op.LHS.second || Op.RHS.second) &&
825 "At least one operand must be complex!");
827 // If either of the operands is a real rather than a complex, the
828 // imaginary component is ignored when computing the real component of the
829 // result.
830 ResR = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul.rl");
832 ResI = Op.LHS.second
833 ? Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul.il")
834 : Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul.ir");
835 } else {
836 assert(Op.LHS.second && Op.RHS.second &&
837 "Both operands of integer complex operators must be complex!");
838 Value *ResRl = Builder.CreateMul(Op.LHS.first, Op.RHS.first, "mul.rl");
839 Value *ResRr = Builder.CreateMul(Op.LHS.second, Op.RHS.second, "mul.rr");
840 ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
842 Value *ResIl = Builder.CreateMul(Op.LHS.second, Op.RHS.first, "mul.il");
843 Value *ResIr = Builder.CreateMul(Op.LHS.first, Op.RHS.second, "mul.ir");
844 ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
846 return ComplexPairTy(ResR, ResI);
849 // See C11 Annex G.5.1 for the semantics of multiplicative operators on complex
850 // typed values.
851 ComplexPairTy ComplexExprEmitter::EmitBinDiv(const BinOpInfo &Op) {
852 llvm::Value *LHSr = Op.LHS.first, *LHSi = Op.LHS.second;
853 llvm::Value *RHSr = Op.RHS.first, *RHSi = Op.RHS.second;
855 llvm::Value *DSTr, *DSTi;
856 if (LHSr->getType()->isFloatingPointTy()) {
857 // If we have a complex operand on the RHS and FastMath is not allowed, we
858 // delegate to a libcall to handle all of the complexities and minimize
859 // underflow/overflow cases. When FastMath is allowed we construct the
860 // divide inline using the same algorithm as for integer operands.
862 // FIXME: We would be able to avoid the libcall in many places if we
863 // supported imaginary types in addition to complex types.
864 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Op.FPFeatures);
865 if (RHSi && !CGF.getLangOpts().FastMath) {
866 BinOpInfo LibCallOp = Op;
867 // If LHS was a real, supply a null imaginary part.
868 if (!LHSi)
869 LibCallOp.LHS.second = llvm::Constant::getNullValue(LHSr->getType());
871 switch (LHSr->getType()->getTypeID()) {
872 default:
873 llvm_unreachable("Unsupported floating point type!");
874 case llvm::Type::HalfTyID:
875 return EmitComplexBinOpLibCall("__divhc3", LibCallOp);
876 case llvm::Type::FloatTyID:
877 return EmitComplexBinOpLibCall("__divsc3", LibCallOp);
878 case llvm::Type::DoubleTyID:
879 return EmitComplexBinOpLibCall("__divdc3", LibCallOp);
880 case llvm::Type::PPC_FP128TyID:
881 return EmitComplexBinOpLibCall("__divtc3", LibCallOp);
882 case llvm::Type::X86_FP80TyID:
883 return EmitComplexBinOpLibCall("__divxc3", LibCallOp);
884 case llvm::Type::FP128TyID:
885 return EmitComplexBinOpLibCall("__divtc3", LibCallOp);
887 } else if (RHSi) {
888 if (!LHSi)
889 LHSi = llvm::Constant::getNullValue(RHSi->getType());
891 // (a+ib) / (c+id) = ((ac+bd)/(cc+dd)) + i((bc-ad)/(cc+dd))
892 llvm::Value *AC = Builder.CreateFMul(LHSr, RHSr); // a*c
893 llvm::Value *BD = Builder.CreateFMul(LHSi, RHSi); // b*d
894 llvm::Value *ACpBD = Builder.CreateFAdd(AC, BD); // ac+bd
896 llvm::Value *CC = Builder.CreateFMul(RHSr, RHSr); // c*c
897 llvm::Value *DD = Builder.CreateFMul(RHSi, RHSi); // d*d
898 llvm::Value *CCpDD = Builder.CreateFAdd(CC, DD); // cc+dd
900 llvm::Value *BC = Builder.CreateFMul(LHSi, RHSr); // b*c
901 llvm::Value *AD = Builder.CreateFMul(LHSr, RHSi); // a*d
902 llvm::Value *BCmAD = Builder.CreateFSub(BC, AD); // bc-ad
904 DSTr = Builder.CreateFDiv(ACpBD, CCpDD);
905 DSTi = Builder.CreateFDiv(BCmAD, CCpDD);
906 } else {
907 assert(LHSi && "Can have at most one non-complex operand!");
909 DSTr = Builder.CreateFDiv(LHSr, RHSr);
910 DSTi = Builder.CreateFDiv(LHSi, RHSr);
912 } else {
913 assert(Op.LHS.second && Op.RHS.second &&
914 "Both operands of integer complex operators must be complex!");
915 // (a+ib) / (c+id) = ((ac+bd)/(cc+dd)) + i((bc-ad)/(cc+dd))
916 llvm::Value *Tmp1 = Builder.CreateMul(LHSr, RHSr); // a*c
917 llvm::Value *Tmp2 = Builder.CreateMul(LHSi, RHSi); // b*d
918 llvm::Value *Tmp3 = Builder.CreateAdd(Tmp1, Tmp2); // ac+bd
920 llvm::Value *Tmp4 = Builder.CreateMul(RHSr, RHSr); // c*c
921 llvm::Value *Tmp5 = Builder.CreateMul(RHSi, RHSi); // d*d
922 llvm::Value *Tmp6 = Builder.CreateAdd(Tmp4, Tmp5); // cc+dd
924 llvm::Value *Tmp7 = Builder.CreateMul(LHSi, RHSr); // b*c
925 llvm::Value *Tmp8 = Builder.CreateMul(LHSr, RHSi); // a*d
926 llvm::Value *Tmp9 = Builder.CreateSub(Tmp7, Tmp8); // bc-ad
928 if (Op.Ty->castAs<ComplexType>()->getElementType()->isUnsignedIntegerType()) {
929 DSTr = Builder.CreateUDiv(Tmp3, Tmp6);
930 DSTi = Builder.CreateUDiv(Tmp9, Tmp6);
931 } else {
932 DSTr = Builder.CreateSDiv(Tmp3, Tmp6);
933 DSTi = Builder.CreateSDiv(Tmp9, Tmp6);
937 return ComplexPairTy(DSTr, DSTi);
940 ComplexPairTy CodeGenFunction::EmitUnPromotedValue(ComplexPairTy result,
941 QualType UnPromotionType) {
942 llvm::Type *ComplexElementTy =
943 ConvertType(UnPromotionType->castAs<ComplexType>()->getElementType());
944 if (result.first)
945 result.first =
946 Builder.CreateFPTrunc(result.first, ComplexElementTy, "unpromotion");
947 if (result.second)
948 result.second =
949 Builder.CreateFPTrunc(result.second, ComplexElementTy, "unpromotion");
950 return result;
953 ComplexPairTy CodeGenFunction::EmitPromotedValue(ComplexPairTy result,
954 QualType PromotionType) {
955 llvm::Type *ComplexElementTy =
956 ConvertType(PromotionType->castAs<ComplexType>()->getElementType());
957 if (result.first)
958 result.first = Builder.CreateFPExt(result.first, ComplexElementTy, "ext");
959 if (result.second)
960 result.second = Builder.CreateFPExt(result.second, ComplexElementTy, "ext");
962 return result;
965 ComplexPairTy ComplexExprEmitter::EmitPromoted(const Expr *E,
966 QualType PromotionType) {
967 E = E->IgnoreParens();
968 if (auto BO = dyn_cast<BinaryOperator>(E)) {
969 switch (BO->getOpcode()) {
970 #define HANDLE_BINOP(OP) \
971 case BO_##OP: \
972 return EmitBin##OP(EmitBinOps(BO, PromotionType));
973 HANDLE_BINOP(Add)
974 HANDLE_BINOP(Sub)
975 HANDLE_BINOP(Mul)
976 HANDLE_BINOP(Div)
977 #undef HANDLE_BINOP
978 default:
979 break;
981 } else if (auto UO = dyn_cast<UnaryOperator>(E)) {
982 switch (UO->getOpcode()) {
983 case UO_Minus:
984 return VisitMinus(UO, PromotionType);
985 case UO_Plus:
986 return VisitPlus(UO, PromotionType);
987 default:
988 break;
991 auto result = Visit(const_cast<Expr *>(E));
992 if (!PromotionType.isNull())
993 return CGF.EmitPromotedValue(result, PromotionType);
994 else
995 return result;
998 ComplexPairTy CodeGenFunction::EmitPromotedComplexExpr(const Expr *E,
999 QualType DstTy) {
1000 return ComplexExprEmitter(*this).EmitPromoted(E, DstTy);
1003 ComplexPairTy
1004 ComplexExprEmitter::EmitPromotedComplexOperand(const Expr *E,
1005 QualType OverallPromotionType) {
1006 if (E->getType()->isAnyComplexType()) {
1007 if (!OverallPromotionType.isNull())
1008 return CGF.EmitPromotedComplexExpr(E, OverallPromotionType);
1009 else
1010 return Visit(const_cast<Expr *>(E));
1011 } else {
1012 if (!OverallPromotionType.isNull()) {
1013 QualType ComplexElementTy =
1014 OverallPromotionType->castAs<ComplexType>()->getElementType();
1015 return ComplexPairTy(CGF.EmitPromotedScalarExpr(E, ComplexElementTy),
1016 nullptr);
1017 } else {
1018 return ComplexPairTy(CGF.EmitScalarExpr(E), nullptr);
1023 ComplexExprEmitter::BinOpInfo
1024 ComplexExprEmitter::EmitBinOps(const BinaryOperator *E,
1025 QualType PromotionType) {
1026 TestAndClearIgnoreReal();
1027 TestAndClearIgnoreImag();
1028 BinOpInfo Ops;
1030 Ops.LHS = EmitPromotedComplexOperand(E->getLHS(), PromotionType);
1031 Ops.RHS = EmitPromotedComplexOperand(E->getRHS(), PromotionType);
1032 if (!PromotionType.isNull())
1033 Ops.Ty = PromotionType;
1034 else
1035 Ops.Ty = E->getType();
1036 Ops.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());
1037 return Ops;
1041 LValue ComplexExprEmitter::
1042 EmitCompoundAssignLValue(const CompoundAssignOperator *E,
1043 ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo&),
1044 RValue &Val) {
1045 TestAndClearIgnoreReal();
1046 TestAndClearIgnoreImag();
1047 QualType LHSTy = E->getLHS()->getType();
1048 if (const AtomicType *AT = LHSTy->getAs<AtomicType>())
1049 LHSTy = AT->getValueType();
1051 BinOpInfo OpInfo;
1052 OpInfo.FPFeatures = E->getFPFeaturesInEffect(CGF.getLangOpts());
1053 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, OpInfo.FPFeatures);
1055 // Load the RHS and LHS operands.
1056 // __block variables need to have the rhs evaluated first, plus this should
1057 // improve codegen a little.
1058 QualType PromotionTypeCR;
1059 PromotionTypeCR = getPromotionType(E->getComputationResultType());
1060 if (PromotionTypeCR.isNull())
1061 PromotionTypeCR = E->getComputationResultType();
1062 OpInfo.Ty = PromotionTypeCR;
1063 QualType ComplexElementTy =
1064 OpInfo.Ty->castAs<ComplexType>()->getElementType();
1065 QualType PromotionTypeRHS = getPromotionType(E->getRHS()->getType());
1067 // The RHS should have been converted to the computation type.
1068 if (E->getRHS()->getType()->isRealFloatingType()) {
1069 if (!PromotionTypeRHS.isNull())
1070 OpInfo.RHS = ComplexPairTy(
1071 CGF.EmitPromotedScalarExpr(E->getRHS(), PromotionTypeRHS), nullptr);
1072 else {
1073 assert(CGF.getContext().hasSameUnqualifiedType(ComplexElementTy,
1074 E->getRHS()->getType()));
1076 OpInfo.RHS = ComplexPairTy(CGF.EmitScalarExpr(E->getRHS()), nullptr);
1078 } else {
1079 if (!PromotionTypeRHS.isNull()) {
1080 OpInfo.RHS = ComplexPairTy(
1081 CGF.EmitPromotedComplexExpr(E->getRHS(), PromotionTypeRHS));
1082 } else {
1083 assert(CGF.getContext().hasSameUnqualifiedType(OpInfo.Ty,
1084 E->getRHS()->getType()));
1085 OpInfo.RHS = Visit(E->getRHS());
1089 LValue LHS = CGF.EmitLValue(E->getLHS());
1091 // Load from the l-value and convert it.
1092 SourceLocation Loc = E->getExprLoc();
1093 QualType PromotionTypeLHS = getPromotionType(E->getComputationLHSType());
1094 if (LHSTy->isAnyComplexType()) {
1095 ComplexPairTy LHSVal = EmitLoadOfLValue(LHS, Loc);
1096 if (!PromotionTypeLHS.isNull())
1097 OpInfo.LHS =
1098 EmitComplexToComplexCast(LHSVal, LHSTy, PromotionTypeLHS, Loc);
1099 else
1100 OpInfo.LHS = EmitComplexToComplexCast(LHSVal, LHSTy, OpInfo.Ty, Loc);
1101 } else {
1102 llvm::Value *LHSVal = CGF.EmitLoadOfScalar(LHS, Loc);
1103 // For floating point real operands we can directly pass the scalar form
1104 // to the binary operator emission and potentially get more efficient code.
1105 if (LHSTy->isRealFloatingType()) {
1106 QualType PromotedComplexElementTy;
1107 if (!PromotionTypeLHS.isNull()) {
1108 PromotedComplexElementTy =
1109 cast<ComplexType>(PromotionTypeLHS)->getElementType();
1110 if (!CGF.getContext().hasSameUnqualifiedType(PromotedComplexElementTy,
1111 PromotionTypeLHS))
1112 LHSVal = CGF.EmitScalarConversion(LHSVal, LHSTy,
1113 PromotedComplexElementTy, Loc);
1114 } else {
1115 if (!CGF.getContext().hasSameUnqualifiedType(ComplexElementTy, LHSTy))
1116 LHSVal =
1117 CGF.EmitScalarConversion(LHSVal, LHSTy, ComplexElementTy, Loc);
1119 OpInfo.LHS = ComplexPairTy(LHSVal, nullptr);
1120 } else {
1121 OpInfo.LHS = EmitScalarToComplexCast(LHSVal, LHSTy, OpInfo.Ty, Loc);
1125 // Expand the binary operator.
1126 ComplexPairTy Result = (this->*Func)(OpInfo);
1128 // Truncate the result and store it into the LHS lvalue.
1129 if (LHSTy->isAnyComplexType()) {
1130 ComplexPairTy ResVal =
1131 EmitComplexToComplexCast(Result, OpInfo.Ty, LHSTy, Loc);
1132 EmitStoreOfComplex(ResVal, LHS, /*isInit*/ false);
1133 Val = RValue::getComplex(ResVal);
1134 } else {
1135 llvm::Value *ResVal =
1136 CGF.EmitComplexToScalarConversion(Result, OpInfo.Ty, LHSTy, Loc);
1137 CGF.EmitStoreOfScalar(ResVal, LHS, /*isInit*/ false);
1138 Val = RValue::get(ResVal);
1141 return LHS;
1144 // Compound assignments.
1145 ComplexPairTy ComplexExprEmitter::
1146 EmitCompoundAssign(const CompoundAssignOperator *E,
1147 ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo&)){
1148 RValue Val;
1149 LValue LV = EmitCompoundAssignLValue(E, Func, Val);
1151 // The result of an assignment in C is the assigned r-value.
1152 if (!CGF.getLangOpts().CPlusPlus)
1153 return Val.getComplexVal();
1155 // If the lvalue is non-volatile, return the computed value of the assignment.
1156 if (!LV.isVolatileQualified())
1157 return Val.getComplexVal();
1159 return EmitLoadOfLValue(LV, E->getExprLoc());
1162 LValue ComplexExprEmitter::EmitBinAssignLValue(const BinaryOperator *E,
1163 ComplexPairTy &Val) {
1164 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
1165 E->getRHS()->getType()) &&
1166 "Invalid assignment");
1167 TestAndClearIgnoreReal();
1168 TestAndClearIgnoreImag();
1170 // Emit the RHS. __block variables need the RHS evaluated first.
1171 Val = Visit(E->getRHS());
1173 // Compute the address to store into.
1174 LValue LHS = CGF.EmitLValue(E->getLHS());
1176 // Store the result value into the LHS lvalue.
1177 EmitStoreOfComplex(Val, LHS, /*isInit*/ false);
1179 return LHS;
1182 ComplexPairTy ComplexExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1183 ComplexPairTy Val;
1184 LValue LV = EmitBinAssignLValue(E, Val);
1186 // The result of an assignment in C is the assigned r-value.
1187 if (!CGF.getLangOpts().CPlusPlus)
1188 return Val;
1190 // If the lvalue is non-volatile, return the computed value of the assignment.
1191 if (!LV.isVolatileQualified())
1192 return Val;
1194 return EmitLoadOfLValue(LV, E->getExprLoc());
1197 ComplexPairTy ComplexExprEmitter::VisitBinComma(const BinaryOperator *E) {
1198 CGF.EmitIgnoredExpr(E->getLHS());
1199 return Visit(E->getRHS());
1202 ComplexPairTy ComplexExprEmitter::
1203 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
1204 TestAndClearIgnoreReal();
1205 TestAndClearIgnoreImag();
1206 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1207 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
1208 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
1210 // Bind the common expression if necessary.
1211 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
1214 CodeGenFunction::ConditionalEvaluation eval(CGF);
1215 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
1216 CGF.getProfileCount(E));
1218 eval.begin(CGF);
1219 CGF.EmitBlock(LHSBlock);
1220 CGF.incrementProfileCounter(E);
1221 ComplexPairTy LHS = Visit(E->getTrueExpr());
1222 LHSBlock = Builder.GetInsertBlock();
1223 CGF.EmitBranch(ContBlock);
1224 eval.end(CGF);
1226 eval.begin(CGF);
1227 CGF.EmitBlock(RHSBlock);
1228 ComplexPairTy RHS = Visit(E->getFalseExpr());
1229 RHSBlock = Builder.GetInsertBlock();
1230 CGF.EmitBlock(ContBlock);
1231 eval.end(CGF);
1233 // Create a PHI node for the real part.
1234 llvm::PHINode *RealPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.r");
1235 RealPN->addIncoming(LHS.first, LHSBlock);
1236 RealPN->addIncoming(RHS.first, RHSBlock);
1238 // Create a PHI node for the imaginary part.
1239 llvm::PHINode *ImagPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.i");
1240 ImagPN->addIncoming(LHS.second, LHSBlock);
1241 ImagPN->addIncoming(RHS.second, RHSBlock);
1243 return ComplexPairTy(RealPN, ImagPN);
1246 ComplexPairTy ComplexExprEmitter::VisitChooseExpr(ChooseExpr *E) {
1247 return Visit(E->getChosenSubExpr());
1250 ComplexPairTy ComplexExprEmitter::VisitInitListExpr(InitListExpr *E) {
1251 bool Ignore = TestAndClearIgnoreReal();
1252 (void)Ignore;
1253 assert (Ignore == false && "init list ignored");
1254 Ignore = TestAndClearIgnoreImag();
1255 (void)Ignore;
1256 assert (Ignore == false && "init list ignored");
1258 if (E->getNumInits() == 2) {
1259 llvm::Value *Real = CGF.EmitScalarExpr(E->getInit(0));
1260 llvm::Value *Imag = CGF.EmitScalarExpr(E->getInit(1));
1261 return ComplexPairTy(Real, Imag);
1262 } else if (E->getNumInits() == 1) {
1263 return Visit(E->getInit(0));
1266 // Empty init list initializes to null
1267 assert(E->getNumInits() == 0 && "Unexpected number of inits");
1268 QualType Ty = E->getType()->castAs<ComplexType>()->getElementType();
1269 llvm::Type* LTy = CGF.ConvertType(Ty);
1270 llvm::Value* zeroConstant = llvm::Constant::getNullValue(LTy);
1271 return ComplexPairTy(zeroConstant, zeroConstant);
1274 ComplexPairTy ComplexExprEmitter::VisitVAArgExpr(VAArgExpr *E) {
1275 Address ArgValue = Address::invalid();
1276 Address ArgPtr = CGF.EmitVAArg(E, ArgValue);
1278 if (!ArgPtr.isValid()) {
1279 CGF.ErrorUnsupported(E, "complex va_arg expression");
1280 llvm::Type *EltTy =
1281 CGF.ConvertType(E->getType()->castAs<ComplexType>()->getElementType());
1282 llvm::Value *U = llvm::UndefValue::get(EltTy);
1283 return ComplexPairTy(U, U);
1286 return EmitLoadOfLValue(CGF.MakeAddrLValue(ArgPtr, E->getType()),
1287 E->getExprLoc());
1290 //===----------------------------------------------------------------------===//
1291 // Entry Point into this File
1292 //===----------------------------------------------------------------------===//
1294 /// EmitComplexExpr - Emit the computation of the specified expression of
1295 /// complex type, ignoring the result.
1296 ComplexPairTy CodeGenFunction::EmitComplexExpr(const Expr *E, bool IgnoreReal,
1297 bool IgnoreImag) {
1298 assert(E && getComplexType(E->getType()) &&
1299 "Invalid complex expression to emit");
1301 return ComplexExprEmitter(*this, IgnoreReal, IgnoreImag)
1302 .Visit(const_cast<Expr *>(E));
1305 void CodeGenFunction::EmitComplexExprIntoLValue(const Expr *E, LValue dest,
1306 bool isInit) {
1307 assert(E && getComplexType(E->getType()) &&
1308 "Invalid complex expression to emit");
1309 ComplexExprEmitter Emitter(*this);
1310 ComplexPairTy Val = Emitter.Visit(const_cast<Expr*>(E));
1311 Emitter.EmitStoreOfComplex(Val, dest, isInit);
1314 /// EmitStoreOfComplex - Store a complex number into the specified l-value.
1315 void CodeGenFunction::EmitStoreOfComplex(ComplexPairTy V, LValue dest,
1316 bool isInit) {
1317 ComplexExprEmitter(*this).EmitStoreOfComplex(V, dest, isInit);
1320 /// EmitLoadOfComplex - Load a complex number from the specified address.
1321 ComplexPairTy CodeGenFunction::EmitLoadOfComplex(LValue src,
1322 SourceLocation loc) {
1323 return ComplexExprEmitter(*this).EmitLoadOfLValue(src, loc);
1326 LValue CodeGenFunction::EmitComplexAssignmentLValue(const BinaryOperator *E) {
1327 assert(E->getOpcode() == BO_Assign);
1328 ComplexPairTy Val; // ignored
1329 LValue LVal = ComplexExprEmitter(*this).EmitBinAssignLValue(E, Val);
1330 if (getLangOpts().OpenMP)
1331 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
1332 E->getLHS());
1333 return LVal;
1336 typedef ComplexPairTy (ComplexExprEmitter::*CompoundFunc)(
1337 const ComplexExprEmitter::BinOpInfo &);
1339 static CompoundFunc getComplexOp(BinaryOperatorKind Op) {
1340 switch (Op) {
1341 case BO_MulAssign: return &ComplexExprEmitter::EmitBinMul;
1342 case BO_DivAssign: return &ComplexExprEmitter::EmitBinDiv;
1343 case BO_SubAssign: return &ComplexExprEmitter::EmitBinSub;
1344 case BO_AddAssign: return &ComplexExprEmitter::EmitBinAdd;
1345 default:
1346 llvm_unreachable("unexpected complex compound assignment");
1350 LValue CodeGenFunction::
1351 EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E) {
1352 CompoundFunc Op = getComplexOp(E->getOpcode());
1353 RValue Val;
1354 return ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);
1357 LValue CodeGenFunction::
1358 EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
1359 llvm::Value *&Result) {
1360 CompoundFunc Op = getComplexOp(E->getOpcode());
1361 RValue Val;
1362 LValue Ret = ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);
1363 Result = Val.getScalarVal();
1364 return Ret;