1 //===--- CGExprComplex.cpp - Emit LLVM Code for Complex Exprs -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code to emit Expr nodes with complex types as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CodeGenModule.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/StmtVisitor.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/MDBuilder.h"
24 #include "llvm/IR/Metadata.h"
25 #include <algorithm>
26 using namespace clang;
27 using namespace CodeGen;
28 
29 //===----------------------------------------------------------------------===//
30 //                        Complex Expression Emitter
31 //===----------------------------------------------------------------------===//
32 
33 typedef CodeGenFunction::ComplexPairTy ComplexPairTy;
34 
35 /// Return the complex type that we are meant to emit.
getComplexType(QualType type)36 static const ComplexType *getComplexType(QualType type) {
37   type = type.getCanonicalType();
38   if (const ComplexType *comp = dyn_cast<ComplexType>(type)) {
39     return comp;
40   } else {
41     return cast<ComplexType>(cast<AtomicType>(type)->getValueType());
42   }
43 }
44 
45 namespace  {
46 class ComplexExprEmitter
47   : public StmtVisitor<ComplexExprEmitter, ComplexPairTy> {
48   CodeGenFunction &CGF;
49   CGBuilderTy &Builder;
50   bool IgnoreReal;
51   bool IgnoreImag;
52 public:
ComplexExprEmitter(CodeGenFunction & cgf,bool ir=false,bool ii=false)53   ComplexExprEmitter(CodeGenFunction &cgf, bool ir=false, bool ii=false)
54     : CGF(cgf), Builder(CGF.Builder), IgnoreReal(ir), IgnoreImag(ii) {
55   }
56 
57 
58   //===--------------------------------------------------------------------===//
59   //                               Utilities
60   //===--------------------------------------------------------------------===//
61 
TestAndClearIgnoreReal()62   bool TestAndClearIgnoreReal() {
63     bool I = IgnoreReal;
64     IgnoreReal = false;
65     return I;
66   }
TestAndClearIgnoreImag()67   bool TestAndClearIgnoreImag() {
68     bool I = IgnoreImag;
69     IgnoreImag = false;
70     return I;
71   }
72 
73   /// EmitLoadOfLValue - Given an expression with complex type that represents a
74   /// value l-value, this method emits the address of the l-value, then loads
75   /// and returns the result.
EmitLoadOfLValue(const Expr * E)76   ComplexPairTy EmitLoadOfLValue(const Expr *E) {
77     return EmitLoadOfLValue(CGF.EmitLValue(E), E->getExprLoc());
78   }
79 
80   ComplexPairTy EmitLoadOfLValue(LValue LV, SourceLocation Loc);
81 
82   /// EmitStoreOfComplex - Store the specified real/imag parts into the
83   /// specified value pointer.
84   void EmitStoreOfComplex(ComplexPairTy Val, LValue LV, bool isInit);
85 
86   /// Emit a cast from complex value Val to DestType.
87   ComplexPairTy EmitComplexToComplexCast(ComplexPairTy Val, QualType SrcType,
88                                          QualType DestType, SourceLocation Loc);
89   /// Emit a cast from scalar value Val to DestType.
90   ComplexPairTy EmitScalarToComplexCast(llvm::Value *Val, QualType SrcType,
91                                         QualType DestType, SourceLocation Loc);
92 
93   //===--------------------------------------------------------------------===//
94   //                            Visitor Methods
95   //===--------------------------------------------------------------------===//
96 
Visit(Expr * E)97   ComplexPairTy Visit(Expr *E) {
98     ApplyDebugLocation DL(CGF, E);
99     return StmtVisitor<ComplexExprEmitter, ComplexPairTy>::Visit(E);
100   }
101 
VisitStmt(Stmt * S)102   ComplexPairTy VisitStmt(Stmt *S) {
103     S->dump(CGF.getContext().getSourceManager());
104     llvm_unreachable("Stmt can't have complex result type!");
105   }
106   ComplexPairTy VisitExpr(Expr *S);
VisitParenExpr(ParenExpr * PE)107   ComplexPairTy VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr());}
VisitGenericSelectionExpr(GenericSelectionExpr * GE)108   ComplexPairTy VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
109     return Visit(GE->getResultExpr());
110   }
111   ComplexPairTy VisitImaginaryLiteral(const ImaginaryLiteral *IL);
112   ComplexPairTy
VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr * PE)113   VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE) {
114     return Visit(PE->getReplacement());
115   }
116 
117   // l-values.
VisitDeclRefExpr(DeclRefExpr * E)118   ComplexPairTy VisitDeclRefExpr(DeclRefExpr *E) {
119     if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
120       if (result.isReference())
121         return EmitLoadOfLValue(result.getReferenceLValue(CGF, E),
122                                 E->getExprLoc());
123 
124       llvm::Constant *pair = result.getValue();
125       return ComplexPairTy(pair->getAggregateElement(0U),
126                            pair->getAggregateElement(1U));
127     }
128     return EmitLoadOfLValue(E);
129   }
VisitObjCIvarRefExpr(ObjCIvarRefExpr * E)130   ComplexPairTy VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
131     return EmitLoadOfLValue(E);
132   }
VisitObjCMessageExpr(ObjCMessageExpr * E)133   ComplexPairTy VisitObjCMessageExpr(ObjCMessageExpr *E) {
134     return CGF.EmitObjCMessageExpr(E).getComplexVal();
135   }
VisitArraySubscriptExpr(Expr * E)136   ComplexPairTy VisitArraySubscriptExpr(Expr *E) { return EmitLoadOfLValue(E); }
VisitMemberExpr(const Expr * E)137   ComplexPairTy VisitMemberExpr(const Expr *E) { return EmitLoadOfLValue(E); }
VisitOpaqueValueExpr(OpaqueValueExpr * E)138   ComplexPairTy VisitOpaqueValueExpr(OpaqueValueExpr *E) {
139     if (E->isGLValue())
140       return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E), E->getExprLoc());
141     return CGF.getOpaqueRValueMapping(E).getComplexVal();
142   }
143 
VisitPseudoObjectExpr(PseudoObjectExpr * E)144   ComplexPairTy VisitPseudoObjectExpr(PseudoObjectExpr *E) {
145     return CGF.EmitPseudoObjectRValue(E).getComplexVal();
146   }
147 
148   // FIXME: CompoundLiteralExpr
149 
150   ComplexPairTy EmitCast(CastKind CK, Expr *Op, QualType DestTy);
VisitImplicitCastExpr(ImplicitCastExpr * E)151   ComplexPairTy VisitImplicitCastExpr(ImplicitCastExpr *E) {
152     // Unlike for scalars, we don't have to worry about function->ptr demotion
153     // here.
154     return EmitCast(E->getCastKind(), E->getSubExpr(), E->getType());
155   }
VisitCastExpr(CastExpr * E)156   ComplexPairTy VisitCastExpr(CastExpr *E) {
157     if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
158       CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
159     return EmitCast(E->getCastKind(), E->getSubExpr(), E->getType());
160   }
161   ComplexPairTy VisitCallExpr(const CallExpr *E);
162   ComplexPairTy VisitStmtExpr(const StmtExpr *E);
163 
164   // Operators.
VisitPrePostIncDec(const UnaryOperator * E,bool isInc,bool isPre)165   ComplexPairTy VisitPrePostIncDec(const UnaryOperator *E,
166                                    bool isInc, bool isPre) {
167     LValue LV = CGF.EmitLValue(E->getSubExpr());
168     return CGF.EmitComplexPrePostIncDec(E, LV, isInc, isPre);
169   }
VisitUnaryPostDec(const UnaryOperator * E)170   ComplexPairTy VisitUnaryPostDec(const UnaryOperator *E) {
171     return VisitPrePostIncDec(E, false, false);
172   }
VisitUnaryPostInc(const UnaryOperator * E)173   ComplexPairTy VisitUnaryPostInc(const UnaryOperator *E) {
174     return VisitPrePostIncDec(E, true, false);
175   }
VisitUnaryPreDec(const UnaryOperator * E)176   ComplexPairTy VisitUnaryPreDec(const UnaryOperator *E) {
177     return VisitPrePostIncDec(E, false, true);
178   }
VisitUnaryPreInc(const UnaryOperator * E)179   ComplexPairTy VisitUnaryPreInc(const UnaryOperator *E) {
180     return VisitPrePostIncDec(E, true, true);
181   }
VisitUnaryDeref(const Expr * E)182   ComplexPairTy VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
VisitUnaryPlus(const UnaryOperator * E)183   ComplexPairTy VisitUnaryPlus     (const UnaryOperator *E) {
184     TestAndClearIgnoreReal();
185     TestAndClearIgnoreImag();
186     return Visit(E->getSubExpr());
187   }
188   ComplexPairTy VisitUnaryMinus    (const UnaryOperator *E);
189   ComplexPairTy VisitUnaryNot      (const UnaryOperator *E);
190   // LNot,Real,Imag never return complex.
VisitUnaryExtension(const UnaryOperator * E)191   ComplexPairTy VisitUnaryExtension(const UnaryOperator *E) {
192     return Visit(E->getSubExpr());
193   }
VisitCXXDefaultArgExpr(CXXDefaultArgExpr * DAE)194   ComplexPairTy VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
195     return Visit(DAE->getExpr());
196   }
VisitCXXDefaultInitExpr(CXXDefaultInitExpr * DIE)197   ComplexPairTy VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
198     CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
199     return Visit(DIE->getExpr());
200   }
VisitExprWithCleanups(ExprWithCleanups * E)201   ComplexPairTy VisitExprWithCleanups(ExprWithCleanups *E) {
202     CGF.enterFullExpression(E);
203     CodeGenFunction::RunCleanupsScope Scope(CGF);
204     return Visit(E->getSubExpr());
205   }
VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr * E)206   ComplexPairTy VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
207     assert(E->getType()->isAnyComplexType() && "Expected complex type!");
208     QualType Elem = E->getType()->castAs<ComplexType>()->getElementType();
209     llvm::Constant *Null = llvm::Constant::getNullValue(CGF.ConvertType(Elem));
210     return ComplexPairTy(Null, Null);
211   }
VisitImplicitValueInitExpr(ImplicitValueInitExpr * E)212   ComplexPairTy VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
213     assert(E->getType()->isAnyComplexType() && "Expected complex type!");
214     QualType Elem = E->getType()->castAs<ComplexType>()->getElementType();
215     llvm::Constant *Null =
216                        llvm::Constant::getNullValue(CGF.ConvertType(Elem));
217     return ComplexPairTy(Null, Null);
218   }
219 
220   struct BinOpInfo {
221     ComplexPairTy LHS;
222     ComplexPairTy RHS;
223     QualType Ty;  // Computation Type.
224   };
225 
226   BinOpInfo EmitBinOps(const BinaryOperator *E);
227   LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
228                                   ComplexPairTy (ComplexExprEmitter::*Func)
229                                   (const BinOpInfo &),
230                                   RValue &Val);
231   ComplexPairTy EmitCompoundAssign(const CompoundAssignOperator *E,
232                                    ComplexPairTy (ComplexExprEmitter::*Func)
233                                    (const BinOpInfo &));
234 
235   ComplexPairTy EmitBinAdd(const BinOpInfo &Op);
236   ComplexPairTy EmitBinSub(const BinOpInfo &Op);
237   ComplexPairTy EmitBinMul(const BinOpInfo &Op);
238   ComplexPairTy EmitBinDiv(const BinOpInfo &Op);
239 
240   ComplexPairTy EmitComplexBinOpLibCall(StringRef LibCallName,
241                                         const BinOpInfo &Op);
242 
VisitBinAdd(const BinaryOperator * E)243   ComplexPairTy VisitBinAdd(const BinaryOperator *E) {
244     return EmitBinAdd(EmitBinOps(E));
245   }
VisitBinSub(const BinaryOperator * E)246   ComplexPairTy VisitBinSub(const BinaryOperator *E) {
247     return EmitBinSub(EmitBinOps(E));
248   }
VisitBinMul(const BinaryOperator * E)249   ComplexPairTy VisitBinMul(const BinaryOperator *E) {
250     return EmitBinMul(EmitBinOps(E));
251   }
VisitBinDiv(const BinaryOperator * E)252   ComplexPairTy VisitBinDiv(const BinaryOperator *E) {
253     return EmitBinDiv(EmitBinOps(E));
254   }
255 
256   // Compound assignments.
VisitBinAddAssign(const CompoundAssignOperator * E)257   ComplexPairTy VisitBinAddAssign(const CompoundAssignOperator *E) {
258     return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinAdd);
259   }
VisitBinSubAssign(const CompoundAssignOperator * E)260   ComplexPairTy VisitBinSubAssign(const CompoundAssignOperator *E) {
261     return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinSub);
262   }
VisitBinMulAssign(const CompoundAssignOperator * E)263   ComplexPairTy VisitBinMulAssign(const CompoundAssignOperator *E) {
264     return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinMul);
265   }
VisitBinDivAssign(const CompoundAssignOperator * E)266   ComplexPairTy VisitBinDivAssign(const CompoundAssignOperator *E) {
267     return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinDiv);
268   }
269 
270   // GCC rejects rem/and/or/xor for integer complex.
271   // Logical and/or always return int, never complex.
272 
273   // No comparisons produce a complex result.
274 
275   LValue EmitBinAssignLValue(const BinaryOperator *E,
276                              ComplexPairTy &Val);
277   ComplexPairTy VisitBinAssign     (const BinaryOperator *E);
278   ComplexPairTy VisitBinComma      (const BinaryOperator *E);
279 
280 
281   ComplexPairTy
282   VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
283   ComplexPairTy VisitChooseExpr(ChooseExpr *CE);
284 
285   ComplexPairTy VisitInitListExpr(InitListExpr *E);
286 
VisitCompoundLiteralExpr(CompoundLiteralExpr * E)287   ComplexPairTy VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
288     return EmitLoadOfLValue(E);
289   }
290 
291   ComplexPairTy VisitVAArgExpr(VAArgExpr *E);
292 
VisitAtomicExpr(AtomicExpr * E)293   ComplexPairTy VisitAtomicExpr(AtomicExpr *E) {
294     return CGF.EmitAtomicExpr(E).getComplexVal();
295   }
296 };
297 }  // end anonymous namespace.
298 
299 //===----------------------------------------------------------------------===//
300 //                                Utilities
301 //===----------------------------------------------------------------------===//
302 
emitAddrOfRealComponent(Address addr,QualType complexType)303 Address CodeGenFunction::emitAddrOfRealComponent(Address addr,
304                                                  QualType complexType) {
305   CharUnits offset = CharUnits::Zero();
306   return Builder.CreateStructGEP(addr, 0, offset, addr.getName() + ".realp");
307 }
308 
emitAddrOfImagComponent(Address addr,QualType complexType)309 Address CodeGenFunction::emitAddrOfImagComponent(Address addr,
310                                                  QualType complexType) {
311   QualType eltType = complexType->castAs<ComplexType>()->getElementType();
312   CharUnits offset = getContext().getTypeSizeInChars(eltType);
313   return Builder.CreateStructGEP(addr, 1, offset, addr.getName() + ".imagp");
314 }
315 
316 /// EmitLoadOfLValue - Given an RValue reference for a complex, emit code to
317 /// load the real and imaginary pieces, returning them as Real/Imag.
EmitLoadOfLValue(LValue lvalue,SourceLocation loc)318 ComplexPairTy ComplexExprEmitter::EmitLoadOfLValue(LValue lvalue,
319                                                    SourceLocation loc) {
320   assert(lvalue.isSimple() && "non-simple complex l-value?");
321   if (lvalue.getType()->isAtomicType())
322     return CGF.EmitAtomicLoad(lvalue, loc).getComplexVal();
323 
324   Address SrcPtr = lvalue.getAddress();
325   bool isVolatile = lvalue.isVolatileQualified();
326 
327   llvm::Value *Real = nullptr, *Imag = nullptr;
328 
329   if (!IgnoreReal || isVolatile) {
330     Address RealP = CGF.emitAddrOfRealComponent(SrcPtr, lvalue.getType());
331     Real = Builder.CreateLoad(RealP, isVolatile, SrcPtr.getName() + ".real");
332   }
333 
334   if (!IgnoreImag || isVolatile) {
335     Address ImagP = CGF.emitAddrOfImagComponent(SrcPtr, lvalue.getType());
336     Imag = Builder.CreateLoad(ImagP, isVolatile, SrcPtr.getName() + ".imag");
337   }
338 
339   return ComplexPairTy(Real, Imag);
340 }
341 
342 /// EmitStoreOfComplex - Store the specified real/imag parts into the
343 /// specified value pointer.
EmitStoreOfComplex(ComplexPairTy Val,LValue lvalue,bool isInit)344 void ComplexExprEmitter::EmitStoreOfComplex(ComplexPairTy Val, LValue lvalue,
345                                             bool isInit) {
346   if (lvalue.getType()->isAtomicType() ||
347       (!isInit && CGF.LValueIsSuitableForInlineAtomic(lvalue)))
348     return CGF.EmitAtomicStore(RValue::getComplex(Val), lvalue, isInit);
349 
350   Address Ptr = lvalue.getAddress();
351   Address RealPtr = CGF.emitAddrOfRealComponent(Ptr, lvalue.getType());
352   Address ImagPtr = CGF.emitAddrOfImagComponent(Ptr, lvalue.getType());
353 
354   Builder.CreateStore(Val.first, RealPtr, lvalue.isVolatileQualified());
355   Builder.CreateStore(Val.second, ImagPtr, lvalue.isVolatileQualified());
356 }
357 
358 
359 
360 //===----------------------------------------------------------------------===//
361 //                            Visitor Methods
362 //===----------------------------------------------------------------------===//
363 
VisitExpr(Expr * E)364 ComplexPairTy ComplexExprEmitter::VisitExpr(Expr *E) {
365   CGF.ErrorUnsupported(E, "complex expression");
366   llvm::Type *EltTy =
367     CGF.ConvertType(getComplexType(E->getType())->getElementType());
368   llvm::Value *U = llvm::UndefValue::get(EltTy);
369   return ComplexPairTy(U, U);
370 }
371 
372 ComplexPairTy ComplexExprEmitter::
VisitImaginaryLiteral(const ImaginaryLiteral * IL)373 VisitImaginaryLiteral(const ImaginaryLiteral *IL) {
374   llvm::Value *Imag = CGF.EmitScalarExpr(IL->getSubExpr());
375   return ComplexPairTy(llvm::Constant::getNullValue(Imag->getType()), Imag);
376 }
377 
378 
VisitCallExpr(const CallExpr * E)379 ComplexPairTy ComplexExprEmitter::VisitCallExpr(const CallExpr *E) {
380   if (E->getCallReturnType(CGF.getContext())->isReferenceType())
381     return EmitLoadOfLValue(E);
382 
383   return CGF.EmitCallExpr(E).getComplexVal();
384 }
385 
VisitStmtExpr(const StmtExpr * E)386 ComplexPairTy ComplexExprEmitter::VisitStmtExpr(const StmtExpr *E) {
387   CodeGenFunction::StmtExprEvaluation eval(CGF);
388   Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(), true);
389   assert(RetAlloca.isValid() && "Expected complex return value");
390   return EmitLoadOfLValue(CGF.MakeAddrLValue(RetAlloca, E->getType()),
391                           E->getExprLoc());
392 }
393 
394 /// Emit a cast from complex value Val to DestType.
EmitComplexToComplexCast(ComplexPairTy Val,QualType SrcType,QualType DestType,SourceLocation Loc)395 ComplexPairTy ComplexExprEmitter::EmitComplexToComplexCast(ComplexPairTy Val,
396                                                            QualType SrcType,
397                                                            QualType DestType,
398                                                            SourceLocation Loc) {
399   // Get the src/dest element type.
400   SrcType = SrcType->castAs<ComplexType>()->getElementType();
401   DestType = DestType->castAs<ComplexType>()->getElementType();
402 
403   // C99 6.3.1.6: When a value of complex type is converted to another
404   // complex type, both the real and imaginary parts follow the conversion
405   // rules for the corresponding real types.
406   Val.first = CGF.EmitScalarConversion(Val.first, SrcType, DestType, Loc);
407   Val.second = CGF.EmitScalarConversion(Val.second, SrcType, DestType, Loc);
408   return Val;
409 }
410 
EmitScalarToComplexCast(llvm::Value * Val,QualType SrcType,QualType DestType,SourceLocation Loc)411 ComplexPairTy ComplexExprEmitter::EmitScalarToComplexCast(llvm::Value *Val,
412                                                           QualType SrcType,
413                                                           QualType DestType,
414                                                           SourceLocation Loc) {
415   // Convert the input element to the element type of the complex.
416   DestType = DestType->castAs<ComplexType>()->getElementType();
417   Val = CGF.EmitScalarConversion(Val, SrcType, DestType, Loc);
418 
419   // Return (realval, 0).
420   return ComplexPairTy(Val, llvm::Constant::getNullValue(Val->getType()));
421 }
422 
EmitCast(CastKind CK,Expr * Op,QualType DestTy)423 ComplexPairTy ComplexExprEmitter::EmitCast(CastKind CK, Expr *Op,
424                                            QualType DestTy) {
425   switch (CK) {
426   case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
427 
428   // Atomic to non-atomic casts may be more than a no-op for some platforms and
429   // for some types.
430   case CK_AtomicToNonAtomic:
431   case CK_NonAtomicToAtomic:
432   case CK_NoOp:
433   case CK_LValueToRValue:
434   case CK_UserDefinedConversion:
435     return Visit(Op);
436 
437   case CK_LValueBitCast: {
438     LValue origLV = CGF.EmitLValue(Op);
439     Address V = origLV.getAddress();
440     V = Builder.CreateElementBitCast(V, CGF.ConvertType(DestTy));
441     return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy), Op->getExprLoc());
442   }
443 
444   case CK_BitCast:
445   case CK_BaseToDerived:
446   case CK_DerivedToBase:
447   case CK_UncheckedDerivedToBase:
448   case CK_Dynamic:
449   case CK_ToUnion:
450   case CK_ArrayToPointerDecay:
451   case CK_FunctionToPointerDecay:
452   case CK_NullToPointer:
453   case CK_NullToMemberPointer:
454   case CK_BaseToDerivedMemberPointer:
455   case CK_DerivedToBaseMemberPointer:
456   case CK_MemberPointerToBoolean:
457   case CK_ReinterpretMemberPointer:
458   case CK_ConstructorConversion:
459   case CK_IntegralToPointer:
460   case CK_PointerToIntegral:
461   case CK_PointerToBoolean:
462   case CK_ToVoid:
463   case CK_VectorSplat:
464   case CK_IntegralCast:
465   case CK_IntegralToBoolean:
466   case CK_IntegralToFloating:
467   case CK_FloatingToIntegral:
468   case CK_FloatingToBoolean:
469   case CK_FloatingCast:
470   case CK_CPointerToObjCPointerCast:
471   case CK_BlockPointerToObjCPointerCast:
472   case CK_AnyPointerToBlockPointerCast:
473   case CK_ObjCObjectLValueCast:
474   case CK_FloatingComplexToReal:
475   case CK_FloatingComplexToBoolean:
476   case CK_IntegralComplexToReal:
477   case CK_IntegralComplexToBoolean:
478   case CK_ARCProduceObject:
479   case CK_ARCConsumeObject:
480   case CK_ARCReclaimReturnedObject:
481   case CK_ARCExtendBlockObject:
482   case CK_CopyAndAutoreleaseBlockObject:
483   case CK_BuiltinFnToFnPtr:
484   case CK_ZeroToOCLEvent:
485   case CK_AddressSpaceConversion:
486     llvm_unreachable("invalid cast kind for complex value");
487 
488   case CK_FloatingRealToComplex:
489   case CK_IntegralRealToComplex:
490     return EmitScalarToComplexCast(CGF.EmitScalarExpr(Op), Op->getType(),
491                                    DestTy, Op->getExprLoc());
492 
493   case CK_FloatingComplexCast:
494   case CK_FloatingComplexToIntegralComplex:
495   case CK_IntegralComplexCast:
496   case CK_IntegralComplexToFloatingComplex:
497     return EmitComplexToComplexCast(Visit(Op), Op->getType(), DestTy,
498                                     Op->getExprLoc());
499   }
500 
501   llvm_unreachable("unknown cast resulting in complex value");
502 }
503 
VisitUnaryMinus(const UnaryOperator * E)504 ComplexPairTy ComplexExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
505   TestAndClearIgnoreReal();
506   TestAndClearIgnoreImag();
507   ComplexPairTy Op = Visit(E->getSubExpr());
508 
509   llvm::Value *ResR, *ResI;
510   if (Op.first->getType()->isFloatingPointTy()) {
511     ResR = Builder.CreateFNeg(Op.first,  "neg.r");
512     ResI = Builder.CreateFNeg(Op.second, "neg.i");
513   } else {
514     ResR = Builder.CreateNeg(Op.first,  "neg.r");
515     ResI = Builder.CreateNeg(Op.second, "neg.i");
516   }
517   return ComplexPairTy(ResR, ResI);
518 }
519 
VisitUnaryNot(const UnaryOperator * E)520 ComplexPairTy ComplexExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
521   TestAndClearIgnoreReal();
522   TestAndClearIgnoreImag();
523   // ~(a+ib) = a + i*-b
524   ComplexPairTy Op = Visit(E->getSubExpr());
525   llvm::Value *ResI;
526   if (Op.second->getType()->isFloatingPointTy())
527     ResI = Builder.CreateFNeg(Op.second, "conj.i");
528   else
529     ResI = Builder.CreateNeg(Op.second, "conj.i");
530 
531   return ComplexPairTy(Op.first, ResI);
532 }
533 
EmitBinAdd(const BinOpInfo & Op)534 ComplexPairTy ComplexExprEmitter::EmitBinAdd(const BinOpInfo &Op) {
535   llvm::Value *ResR, *ResI;
536 
537   if (Op.LHS.first->getType()->isFloatingPointTy()) {
538     ResR = Builder.CreateFAdd(Op.LHS.first,  Op.RHS.first,  "add.r");
539     if (Op.LHS.second && Op.RHS.second)
540       ResI = Builder.CreateFAdd(Op.LHS.second, Op.RHS.second, "add.i");
541     else
542       ResI = Op.LHS.second ? Op.LHS.second : Op.RHS.second;
543     assert(ResI && "Only one operand may be real!");
544   } else {
545     ResR = Builder.CreateAdd(Op.LHS.first,  Op.RHS.first,  "add.r");
546     assert(Op.LHS.second && Op.RHS.second &&
547            "Both operands of integer complex operators must be complex!");
548     ResI = Builder.CreateAdd(Op.LHS.second, Op.RHS.second, "add.i");
549   }
550   return ComplexPairTy(ResR, ResI);
551 }
552 
EmitBinSub(const BinOpInfo & Op)553 ComplexPairTy ComplexExprEmitter::EmitBinSub(const BinOpInfo &Op) {
554   llvm::Value *ResR, *ResI;
555   if (Op.LHS.first->getType()->isFloatingPointTy()) {
556     ResR = Builder.CreateFSub(Op.LHS.first, Op.RHS.first, "sub.r");
557     if (Op.LHS.second && Op.RHS.second)
558       ResI = Builder.CreateFSub(Op.LHS.second, Op.RHS.second, "sub.i");
559     else
560       ResI = Op.LHS.second ? Op.LHS.second
561                            : Builder.CreateFNeg(Op.RHS.second, "sub.i");
562     assert(ResI && "Only one operand may be real!");
563   } else {
564     ResR = Builder.CreateSub(Op.LHS.first, Op.RHS.first, "sub.r");
565     assert(Op.LHS.second && Op.RHS.second &&
566            "Both operands of integer complex operators must be complex!");
567     ResI = Builder.CreateSub(Op.LHS.second, Op.RHS.second, "sub.i");
568   }
569   return ComplexPairTy(ResR, ResI);
570 }
571 
572 /// \brief Emit a libcall for a binary operation on complex types.
EmitComplexBinOpLibCall(StringRef LibCallName,const BinOpInfo & Op)573 ComplexPairTy ComplexExprEmitter::EmitComplexBinOpLibCall(StringRef LibCallName,
574                                                           const BinOpInfo &Op) {
575   CallArgList Args;
576   Args.add(RValue::get(Op.LHS.first),
577            Op.Ty->castAs<ComplexType>()->getElementType());
578   Args.add(RValue::get(Op.LHS.second),
579            Op.Ty->castAs<ComplexType>()->getElementType());
580   Args.add(RValue::get(Op.RHS.first),
581            Op.Ty->castAs<ComplexType>()->getElementType());
582   Args.add(RValue::get(Op.RHS.second),
583            Op.Ty->castAs<ComplexType>()->getElementType());
584 
585   // We *must* use the full CG function call building logic here because the
586   // complex type has special ABI handling. We also should not forget about
587   // special calling convention which may be used for compiler builtins.
588 
589   // We create a function qualified type to state that this call does not have
590   // any exceptions.
591   FunctionProtoType::ExtProtoInfo EPI;
592   EPI = EPI.withExceptionSpec(
593       FunctionProtoType::ExceptionSpecInfo(EST_BasicNoexcept));
594   SmallVector<QualType, 4> ArgsQTys(
595       4, Op.Ty->castAs<ComplexType>()->getElementType());
596   QualType FQTy = CGF.getContext().getFunctionType(Op.Ty, ArgsQTys, EPI);
597   const CGFunctionInfo &FuncInfo = CGF.CGM.getTypes().arrangeFreeFunctionCall(
598       Args, cast<FunctionType>(FQTy.getTypePtr()), false);
599 
600   llvm::FunctionType *FTy = CGF.CGM.getTypes().GetFunctionType(FuncInfo);
601   llvm::Constant *Func = CGF.CGM.CreateBuiltinFunction(FTy, LibCallName);
602   llvm::Instruction *Call;
603 
604   RValue Res = CGF.EmitCall(FuncInfo, Func, ReturnValueSlot(), Args,
605                             FQTy->getAs<FunctionProtoType>(), &Call);
606   cast<llvm::CallInst>(Call)->setCallingConv(CGF.CGM.getBuiltinCC());
607   return Res.getComplexVal();
608 }
609 
610 /// \brief Lookup the libcall name for a given floating point type complex
611 /// multiply.
getComplexMultiplyLibCallName(llvm::Type * Ty)612 static StringRef getComplexMultiplyLibCallName(llvm::Type *Ty) {
613   switch (Ty->getTypeID()) {
614   default:
615     llvm_unreachable("Unsupported floating point type!");
616   case llvm::Type::HalfTyID:
617     return "__mulhc3";
618   case llvm::Type::FloatTyID:
619     return "__mulsc3";
620   case llvm::Type::DoubleTyID:
621     return "__muldc3";
622   case llvm::Type::PPC_FP128TyID:
623     return "__multc3";
624   case llvm::Type::X86_FP80TyID:
625     return "__mulxc3";
626   case llvm::Type::FP128TyID:
627     return "__multc3";
628   }
629 }
630 
631 // See C11 Annex G.5.1 for the semantics of multiplicative operators on complex
632 // typed values.
EmitBinMul(const BinOpInfo & Op)633 ComplexPairTy ComplexExprEmitter::EmitBinMul(const BinOpInfo &Op) {
634   using llvm::Value;
635   Value *ResR, *ResI;
636   llvm::MDBuilder MDHelper(CGF.getLLVMContext());
637 
638   if (Op.LHS.first->getType()->isFloatingPointTy()) {
639     // The general formulation is:
640     // (a + ib) * (c + id) = (a * c - b * d) + i(a * d + b * c)
641     //
642     // But we can fold away components which would be zero due to a real
643     // operand according to C11 Annex G.5.1p2.
644     // FIXME: C11 also provides for imaginary types which would allow folding
645     // still more of this within the type system.
646 
647     if (Op.LHS.second && Op.RHS.second) {
648       // If both operands are complex, emit the core math directly, and then
649       // test for NaNs. If we find NaNs in the result, we delegate to a libcall
650       // to carefully re-compute the correct infinity representation if
651       // possible. The expectation is that the presence of NaNs here is
652       // *extremely* rare, and so the cost of the libcall is almost irrelevant.
653       // This is good, because the libcall re-computes the core multiplication
654       // exactly the same as we do here and re-tests for NaNs in order to be
655       // a generic complex*complex libcall.
656 
657       // First compute the four products.
658       Value *AC = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul_ac");
659       Value *BD = Builder.CreateFMul(Op.LHS.second, Op.RHS.second, "mul_bd");
660       Value *AD = Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul_ad");
661       Value *BC = Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul_bc");
662 
663       // The real part is the difference of the first two, the imaginary part is
664       // the sum of the second.
665       ResR = Builder.CreateFSub(AC, BD, "mul_r");
666       ResI = Builder.CreateFAdd(AD, BC, "mul_i");
667 
668       // Emit the test for the real part becoming NaN and create a branch to
669       // handle it. We test for NaN by comparing the number to itself.
670       Value *IsRNaN = Builder.CreateFCmpUNO(ResR, ResR, "isnan_cmp");
671       llvm::BasicBlock *ContBB = CGF.createBasicBlock("complex_mul_cont");
672       llvm::BasicBlock *INaNBB = CGF.createBasicBlock("complex_mul_imag_nan");
673       llvm::Instruction *Branch = Builder.CreateCondBr(IsRNaN, INaNBB, ContBB);
674       llvm::BasicBlock *OrigBB = Branch->getParent();
675 
676       // Give hint that we very much don't expect to see NaNs.
677       // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
678       llvm::MDNode *BrWeight = MDHelper.createBranchWeights(1, (1U << 20) - 1);
679       Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);
680 
681       // Now test the imaginary part and create its branch.
682       CGF.EmitBlock(INaNBB);
683       Value *IsINaN = Builder.CreateFCmpUNO(ResI, ResI, "isnan_cmp");
684       llvm::BasicBlock *LibCallBB = CGF.createBasicBlock("complex_mul_libcall");
685       Branch = Builder.CreateCondBr(IsINaN, LibCallBB, ContBB);
686       Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);
687 
688       // Now emit the libcall on this slowest of the slow paths.
689       CGF.EmitBlock(LibCallBB);
690       Value *LibCallR, *LibCallI;
691       std::tie(LibCallR, LibCallI) = EmitComplexBinOpLibCall(
692           getComplexMultiplyLibCallName(Op.LHS.first->getType()), Op);
693       Builder.CreateBr(ContBB);
694 
695       // Finally continue execution by phi-ing together the different
696       // computation paths.
697       CGF.EmitBlock(ContBB);
698       llvm::PHINode *RealPHI = Builder.CreatePHI(ResR->getType(), 3, "real_mul_phi");
699       RealPHI->addIncoming(ResR, OrigBB);
700       RealPHI->addIncoming(ResR, INaNBB);
701       RealPHI->addIncoming(LibCallR, LibCallBB);
702       llvm::PHINode *ImagPHI = Builder.CreatePHI(ResI->getType(), 3, "imag_mul_phi");
703       ImagPHI->addIncoming(ResI, OrigBB);
704       ImagPHI->addIncoming(ResI, INaNBB);
705       ImagPHI->addIncoming(LibCallI, LibCallBB);
706       return ComplexPairTy(RealPHI, ImagPHI);
707     }
708     assert((Op.LHS.second || Op.RHS.second) &&
709            "At least one operand must be complex!");
710 
711     // If either of the operands is a real rather than a complex, the
712     // imaginary component is ignored when computing the real component of the
713     // result.
714     ResR = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul.rl");
715 
716     ResI = Op.LHS.second
717                ? Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul.il")
718                : Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul.ir");
719   } else {
720     assert(Op.LHS.second && Op.RHS.second &&
721            "Both operands of integer complex operators must be complex!");
722     Value *ResRl = Builder.CreateMul(Op.LHS.first, Op.RHS.first, "mul.rl");
723     Value *ResRr = Builder.CreateMul(Op.LHS.second, Op.RHS.second, "mul.rr");
724     ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
725 
726     Value *ResIl = Builder.CreateMul(Op.LHS.second, Op.RHS.first, "mul.il");
727     Value *ResIr = Builder.CreateMul(Op.LHS.first, Op.RHS.second, "mul.ir");
728     ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
729   }
730   return ComplexPairTy(ResR, ResI);
731 }
732 
733 // See C11 Annex G.5.1 for the semantics of multiplicative operators on complex
734 // typed values.
EmitBinDiv(const BinOpInfo & Op)735 ComplexPairTy ComplexExprEmitter::EmitBinDiv(const BinOpInfo &Op) {
736   llvm::Value *LHSr = Op.LHS.first, *LHSi = Op.LHS.second;
737   llvm::Value *RHSr = Op.RHS.first, *RHSi = Op.RHS.second;
738 
739 
740   llvm::Value *DSTr, *DSTi;
741   if (LHSr->getType()->isFloatingPointTy()) {
742     // If we have a complex operand on the RHS, we delegate to a libcall to
743     // handle all of the complexities and minimize underflow/overflow cases.
744     //
745     // FIXME: We would be able to avoid the libcall in many places if we
746     // supported imaginary types in addition to complex types.
747     if (RHSi) {
748       BinOpInfo LibCallOp = Op;
749       // If LHS was a real, supply a null imaginary part.
750       if (!LHSi)
751         LibCallOp.LHS.second = llvm::Constant::getNullValue(LHSr->getType());
752 
753       StringRef LibCallName;
754       switch (LHSr->getType()->getTypeID()) {
755       default:
756         llvm_unreachable("Unsupported floating point type!");
757       case llvm::Type::HalfTyID:
758         return EmitComplexBinOpLibCall("__divhc3", LibCallOp);
759       case llvm::Type::FloatTyID:
760         return EmitComplexBinOpLibCall("__divsc3", LibCallOp);
761       case llvm::Type::DoubleTyID:
762         return EmitComplexBinOpLibCall("__divdc3", LibCallOp);
763       case llvm::Type::PPC_FP128TyID:
764         return EmitComplexBinOpLibCall("__divtc3", LibCallOp);
765       case llvm::Type::X86_FP80TyID:
766         return EmitComplexBinOpLibCall("__divxc3", LibCallOp);
767       case llvm::Type::FP128TyID:
768         return EmitComplexBinOpLibCall("__divtc3", LibCallOp);
769       }
770     }
771     assert(LHSi && "Can have at most one non-complex operand!");
772 
773     DSTr = Builder.CreateFDiv(LHSr, RHSr);
774     DSTi = Builder.CreateFDiv(LHSi, RHSr);
775   } else {
776     assert(Op.LHS.second && Op.RHS.second &&
777            "Both operands of integer complex operators must be complex!");
778     // (a+ib) / (c+id) = ((ac+bd)/(cc+dd)) + i((bc-ad)/(cc+dd))
779     llvm::Value *Tmp1 = Builder.CreateMul(LHSr, RHSr); // a*c
780     llvm::Value *Tmp2 = Builder.CreateMul(LHSi, RHSi); // b*d
781     llvm::Value *Tmp3 = Builder.CreateAdd(Tmp1, Tmp2); // ac+bd
782 
783     llvm::Value *Tmp4 = Builder.CreateMul(RHSr, RHSr); // c*c
784     llvm::Value *Tmp5 = Builder.CreateMul(RHSi, RHSi); // d*d
785     llvm::Value *Tmp6 = Builder.CreateAdd(Tmp4, Tmp5); // cc+dd
786 
787     llvm::Value *Tmp7 = Builder.CreateMul(LHSi, RHSr); // b*c
788     llvm::Value *Tmp8 = Builder.CreateMul(LHSr, RHSi); // a*d
789     llvm::Value *Tmp9 = Builder.CreateSub(Tmp7, Tmp8); // bc-ad
790 
791     if (Op.Ty->castAs<ComplexType>()->getElementType()->isUnsignedIntegerType()) {
792       DSTr = Builder.CreateUDiv(Tmp3, Tmp6);
793       DSTi = Builder.CreateUDiv(Tmp9, Tmp6);
794     } else {
795       DSTr = Builder.CreateSDiv(Tmp3, Tmp6);
796       DSTi = Builder.CreateSDiv(Tmp9, Tmp6);
797     }
798   }
799 
800   return ComplexPairTy(DSTr, DSTi);
801 }
802 
803 ComplexExprEmitter::BinOpInfo
EmitBinOps(const BinaryOperator * E)804 ComplexExprEmitter::EmitBinOps(const BinaryOperator *E) {
805   TestAndClearIgnoreReal();
806   TestAndClearIgnoreImag();
807   BinOpInfo Ops;
808   if (E->getLHS()->getType()->isRealFloatingType())
809     Ops.LHS = ComplexPairTy(CGF.EmitScalarExpr(E->getLHS()), nullptr);
810   else
811     Ops.LHS = Visit(E->getLHS());
812   if (E->getRHS()->getType()->isRealFloatingType())
813     Ops.RHS = ComplexPairTy(CGF.EmitScalarExpr(E->getRHS()), nullptr);
814   else
815     Ops.RHS = Visit(E->getRHS());
816 
817   Ops.Ty = E->getType();
818   return Ops;
819 }
820 
821 
822 LValue ComplexExprEmitter::
EmitCompoundAssignLValue(const CompoundAssignOperator * E,ComplexPairTy (ComplexExprEmitter::* Func)(const BinOpInfo &),RValue & Val)823 EmitCompoundAssignLValue(const CompoundAssignOperator *E,
824           ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo&),
825                          RValue &Val) {
826   TestAndClearIgnoreReal();
827   TestAndClearIgnoreImag();
828   QualType LHSTy = E->getLHS()->getType();
829   if (const AtomicType *AT = LHSTy->getAs<AtomicType>())
830     LHSTy = AT->getValueType();
831 
832   BinOpInfo OpInfo;
833 
834   // Load the RHS and LHS operands.
835   // __block variables need to have the rhs evaluated first, plus this should
836   // improve codegen a little.
837   OpInfo.Ty = E->getComputationResultType();
838   QualType ComplexElementTy = cast<ComplexType>(OpInfo.Ty)->getElementType();
839 
840   // The RHS should have been converted to the computation type.
841   if (E->getRHS()->getType()->isRealFloatingType()) {
842     assert(
843         CGF.getContext()
844             .hasSameUnqualifiedType(ComplexElementTy, E->getRHS()->getType()));
845     OpInfo.RHS = ComplexPairTy(CGF.EmitScalarExpr(E->getRHS()), nullptr);
846   } else {
847     assert(CGF.getContext()
848                .hasSameUnqualifiedType(OpInfo.Ty, E->getRHS()->getType()));
849     OpInfo.RHS = Visit(E->getRHS());
850   }
851 
852   LValue LHS = CGF.EmitLValue(E->getLHS());
853 
854   // Load from the l-value and convert it.
855   SourceLocation Loc = E->getExprLoc();
856   if (LHSTy->isAnyComplexType()) {
857     ComplexPairTy LHSVal = EmitLoadOfLValue(LHS, Loc);
858     OpInfo.LHS = EmitComplexToComplexCast(LHSVal, LHSTy, OpInfo.Ty, Loc);
859   } else {
860     llvm::Value *LHSVal = CGF.EmitLoadOfScalar(LHS, Loc);
861     // For floating point real operands we can directly pass the scalar form
862     // to the binary operator emission and potentially get more efficient code.
863     if (LHSTy->isRealFloatingType()) {
864       if (!CGF.getContext().hasSameUnqualifiedType(ComplexElementTy, LHSTy))
865         LHSVal = CGF.EmitScalarConversion(LHSVal, LHSTy, ComplexElementTy, Loc);
866       OpInfo.LHS = ComplexPairTy(LHSVal, nullptr);
867     } else {
868       OpInfo.LHS = EmitScalarToComplexCast(LHSVal, LHSTy, OpInfo.Ty, Loc);
869     }
870   }
871 
872   // Expand the binary operator.
873   ComplexPairTy Result = (this->*Func)(OpInfo);
874 
875   // Truncate the result and store it into the LHS lvalue.
876   if (LHSTy->isAnyComplexType()) {
877     ComplexPairTy ResVal =
878         EmitComplexToComplexCast(Result, OpInfo.Ty, LHSTy, Loc);
879     EmitStoreOfComplex(ResVal, LHS, /*isInit*/ false);
880     Val = RValue::getComplex(ResVal);
881   } else {
882     llvm::Value *ResVal =
883         CGF.EmitComplexToScalarConversion(Result, OpInfo.Ty, LHSTy, Loc);
884     CGF.EmitStoreOfScalar(ResVal, LHS, /*isInit*/ false);
885     Val = RValue::get(ResVal);
886   }
887 
888   return LHS;
889 }
890 
891 // Compound assignments.
892 ComplexPairTy ComplexExprEmitter::
EmitCompoundAssign(const CompoundAssignOperator * E,ComplexPairTy (ComplexExprEmitter::* Func)(const BinOpInfo &))893 EmitCompoundAssign(const CompoundAssignOperator *E,
894                    ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo&)){
895   RValue Val;
896   LValue LV = EmitCompoundAssignLValue(E, Func, Val);
897 
898   // The result of an assignment in C is the assigned r-value.
899   if (!CGF.getLangOpts().CPlusPlus)
900     return Val.getComplexVal();
901 
902   // If the lvalue is non-volatile, return the computed value of the assignment.
903   if (!LV.isVolatileQualified())
904     return Val.getComplexVal();
905 
906   return EmitLoadOfLValue(LV, E->getExprLoc());
907 }
908 
EmitBinAssignLValue(const BinaryOperator * E,ComplexPairTy & Val)909 LValue ComplexExprEmitter::EmitBinAssignLValue(const BinaryOperator *E,
910                                                ComplexPairTy &Val) {
911   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
912                                                  E->getRHS()->getType()) &&
913          "Invalid assignment");
914   TestAndClearIgnoreReal();
915   TestAndClearIgnoreImag();
916 
917   // Emit the RHS.  __block variables need the RHS evaluated first.
918   Val = Visit(E->getRHS());
919 
920   // Compute the address to store into.
921   LValue LHS = CGF.EmitLValue(E->getLHS());
922 
923   // Store the result value into the LHS lvalue.
924   EmitStoreOfComplex(Val, LHS, /*isInit*/ false);
925 
926   return LHS;
927 }
928 
VisitBinAssign(const BinaryOperator * E)929 ComplexPairTy ComplexExprEmitter::VisitBinAssign(const BinaryOperator *E) {
930   ComplexPairTy Val;
931   LValue LV = EmitBinAssignLValue(E, Val);
932 
933   // The result of an assignment in C is the assigned r-value.
934   if (!CGF.getLangOpts().CPlusPlus)
935     return Val;
936 
937   // If the lvalue is non-volatile, return the computed value of the assignment.
938   if (!LV.isVolatileQualified())
939     return Val;
940 
941   return EmitLoadOfLValue(LV, E->getExprLoc());
942 }
943 
VisitBinComma(const BinaryOperator * E)944 ComplexPairTy ComplexExprEmitter::VisitBinComma(const BinaryOperator *E) {
945   CGF.EmitIgnoredExpr(E->getLHS());
946   return Visit(E->getRHS());
947 }
948 
949 ComplexPairTy ComplexExprEmitter::
VisitAbstractConditionalOperator(const AbstractConditionalOperator * E)950 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
951   TestAndClearIgnoreReal();
952   TestAndClearIgnoreImag();
953   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
954   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
955   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
956 
957   // Bind the common expression if necessary.
958   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
959 
960 
961   CodeGenFunction::ConditionalEvaluation eval(CGF);
962   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
963                            CGF.getProfileCount(E));
964 
965   eval.begin(CGF);
966   CGF.EmitBlock(LHSBlock);
967   CGF.incrementProfileCounter(E);
968   ComplexPairTy LHS = Visit(E->getTrueExpr());
969   LHSBlock = Builder.GetInsertBlock();
970   CGF.EmitBranch(ContBlock);
971   eval.end(CGF);
972 
973   eval.begin(CGF);
974   CGF.EmitBlock(RHSBlock);
975   ComplexPairTy RHS = Visit(E->getFalseExpr());
976   RHSBlock = Builder.GetInsertBlock();
977   CGF.EmitBlock(ContBlock);
978   eval.end(CGF);
979 
980   // Create a PHI node for the real part.
981   llvm::PHINode *RealPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.r");
982   RealPN->addIncoming(LHS.first, LHSBlock);
983   RealPN->addIncoming(RHS.first, RHSBlock);
984 
985   // Create a PHI node for the imaginary part.
986   llvm::PHINode *ImagPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.i");
987   ImagPN->addIncoming(LHS.second, LHSBlock);
988   ImagPN->addIncoming(RHS.second, RHSBlock);
989 
990   return ComplexPairTy(RealPN, ImagPN);
991 }
992 
VisitChooseExpr(ChooseExpr * E)993 ComplexPairTy ComplexExprEmitter::VisitChooseExpr(ChooseExpr *E) {
994   return Visit(E->getChosenSubExpr());
995 }
996 
VisitInitListExpr(InitListExpr * E)997 ComplexPairTy ComplexExprEmitter::VisitInitListExpr(InitListExpr *E) {
998     bool Ignore = TestAndClearIgnoreReal();
999     (void)Ignore;
1000     assert (Ignore == false && "init list ignored");
1001     Ignore = TestAndClearIgnoreImag();
1002     (void)Ignore;
1003     assert (Ignore == false && "init list ignored");
1004 
1005   if (E->getNumInits() == 2) {
1006     llvm::Value *Real = CGF.EmitScalarExpr(E->getInit(0));
1007     llvm::Value *Imag = CGF.EmitScalarExpr(E->getInit(1));
1008     return ComplexPairTy(Real, Imag);
1009   } else if (E->getNumInits() == 1) {
1010     return Visit(E->getInit(0));
1011   }
1012 
1013   // Empty init list intializes to null
1014   assert(E->getNumInits() == 0 && "Unexpected number of inits");
1015   QualType Ty = E->getType()->castAs<ComplexType>()->getElementType();
1016   llvm::Type* LTy = CGF.ConvertType(Ty);
1017   llvm::Value* zeroConstant = llvm::Constant::getNullValue(LTy);
1018   return ComplexPairTy(zeroConstant, zeroConstant);
1019 }
1020 
VisitVAArgExpr(VAArgExpr * E)1021 ComplexPairTy ComplexExprEmitter::VisitVAArgExpr(VAArgExpr *E) {
1022   Address ArgValue = Address::invalid();
1023   Address ArgPtr = CGF.EmitVAArg(E, ArgValue);
1024 
1025   if (!ArgPtr.isValid()) {
1026     CGF.ErrorUnsupported(E, "complex va_arg expression");
1027     llvm::Type *EltTy =
1028       CGF.ConvertType(E->getType()->castAs<ComplexType>()->getElementType());
1029     llvm::Value *U = llvm::UndefValue::get(EltTy);
1030     return ComplexPairTy(U, U);
1031   }
1032 
1033   return EmitLoadOfLValue(CGF.MakeAddrLValue(ArgPtr, E->getType()),
1034                           E->getExprLoc());
1035 }
1036 
1037 //===----------------------------------------------------------------------===//
1038 //                         Entry Point into this File
1039 //===----------------------------------------------------------------------===//
1040 
1041 /// EmitComplexExpr - Emit the computation of the specified expression of
1042 /// complex type, ignoring the result.
EmitComplexExpr(const Expr * E,bool IgnoreReal,bool IgnoreImag)1043 ComplexPairTy CodeGenFunction::EmitComplexExpr(const Expr *E, bool IgnoreReal,
1044                                                bool IgnoreImag) {
1045   assert(E && getComplexType(E->getType()) &&
1046          "Invalid complex expression to emit");
1047 
1048   return ComplexExprEmitter(*this, IgnoreReal, IgnoreImag)
1049       .Visit(const_cast<Expr *>(E));
1050 }
1051 
EmitComplexExprIntoLValue(const Expr * E,LValue dest,bool isInit)1052 void CodeGenFunction::EmitComplexExprIntoLValue(const Expr *E, LValue dest,
1053                                                 bool isInit) {
1054   assert(E && getComplexType(E->getType()) &&
1055          "Invalid complex expression to emit");
1056   ComplexExprEmitter Emitter(*this);
1057   ComplexPairTy Val = Emitter.Visit(const_cast<Expr*>(E));
1058   Emitter.EmitStoreOfComplex(Val, dest, isInit);
1059 }
1060 
1061 /// EmitStoreOfComplex - Store a complex number into the specified l-value.
EmitStoreOfComplex(ComplexPairTy V,LValue dest,bool isInit)1062 void CodeGenFunction::EmitStoreOfComplex(ComplexPairTy V, LValue dest,
1063                                          bool isInit) {
1064   ComplexExprEmitter(*this).EmitStoreOfComplex(V, dest, isInit);
1065 }
1066 
1067 /// EmitLoadOfComplex - Load a complex number from the specified address.
EmitLoadOfComplex(LValue src,SourceLocation loc)1068 ComplexPairTy CodeGenFunction::EmitLoadOfComplex(LValue src,
1069                                                  SourceLocation loc) {
1070   return ComplexExprEmitter(*this).EmitLoadOfLValue(src, loc);
1071 }
1072 
EmitComplexAssignmentLValue(const BinaryOperator * E)1073 LValue CodeGenFunction::EmitComplexAssignmentLValue(const BinaryOperator *E) {
1074   assert(E->getOpcode() == BO_Assign);
1075   ComplexPairTy Val; // ignored
1076   return ComplexExprEmitter(*this).EmitBinAssignLValue(E, Val);
1077 }
1078 
1079 typedef ComplexPairTy (ComplexExprEmitter::*CompoundFunc)(
1080     const ComplexExprEmitter::BinOpInfo &);
1081 
getComplexOp(BinaryOperatorKind Op)1082 static CompoundFunc getComplexOp(BinaryOperatorKind Op) {
1083   switch (Op) {
1084   case BO_MulAssign: return &ComplexExprEmitter::EmitBinMul;
1085   case BO_DivAssign: return &ComplexExprEmitter::EmitBinDiv;
1086   case BO_SubAssign: return &ComplexExprEmitter::EmitBinSub;
1087   case BO_AddAssign: return &ComplexExprEmitter::EmitBinAdd;
1088   default:
1089     llvm_unreachable("unexpected complex compound assignment");
1090   }
1091 }
1092 
1093 LValue CodeGenFunction::
EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator * E)1094 EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E) {
1095   CompoundFunc Op = getComplexOp(E->getOpcode());
1096   RValue Val;
1097   return ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);
1098 }
1099 
1100 LValue CodeGenFunction::
EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator * E,llvm::Value * & Result)1101 EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
1102                                     llvm::Value *&Result) {
1103   CompoundFunc Op = getComplexOp(E->getOpcode());
1104   RValue Val;
1105   LValue Ret = ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);
1106   Result = Val.getScalarVal();
1107   return Ret;
1108 }
1109