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