clang  6.0.0svn
CGExprComplex.cpp
Go to the documentation of this file.
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/StmtVisitor.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/IR/MDBuilder.h"
21 #include "llvm/IR/Metadata.h"
22 #include <algorithm>
23 using namespace clang;
24 using namespace CodeGen;
25 
26 //===----------------------------------------------------------------------===//
27 // Complex Expression Emitter
28 //===----------------------------------------------------------------------===//
29 
31 
32 /// Return the complex type that we are meant to emit.
34  type = type.getCanonicalType();
35  if (const ComplexType *comp = dyn_cast<ComplexType>(type)) {
36  return comp;
37  } else {
38  return cast<ComplexType>(cast<AtomicType>(type)->getValueType());
39  }
40 }
41 
42 namespace {
43 class ComplexExprEmitter
44  : public StmtVisitor<ComplexExprEmitter, ComplexPairTy> {
45  CodeGenFunction &CGF;
46  CGBuilderTy &Builder;
47  bool IgnoreReal;
48  bool IgnoreImag;
49 public:
50  ComplexExprEmitter(CodeGenFunction &cgf, bool ir=false, bool ii=false)
51  : CGF(cgf), Builder(CGF.Builder), IgnoreReal(ir), IgnoreImag(ii) {
52  }
53 
54 
55  //===--------------------------------------------------------------------===//
56  // Utilities
57  //===--------------------------------------------------------------------===//
58 
59  bool TestAndClearIgnoreReal() {
60  bool I = IgnoreReal;
61  IgnoreReal = false;
62  return I;
63  }
64  bool TestAndClearIgnoreImag() {
65  bool I = IgnoreImag;
66  IgnoreImag = false;
67  return I;
68  }
69 
70  /// EmitLoadOfLValue - Given an expression with complex type that represents a
71  /// value l-value, this method emits the address of the l-value, then loads
72  /// and returns the result.
73  ComplexPairTy EmitLoadOfLValue(const Expr *E) {
74  return EmitLoadOfLValue(CGF.EmitLValue(E), E->getExprLoc());
75  }
76 
77  ComplexPairTy EmitLoadOfLValue(LValue LV, SourceLocation Loc);
78 
79  /// EmitStoreOfComplex - Store the specified real/imag parts into the
80  /// specified value pointer.
81  void EmitStoreOfComplex(ComplexPairTy Val, LValue LV, bool isInit);
82 
83  /// Emit a cast from complex value Val to DestType.
84  ComplexPairTy EmitComplexToComplexCast(ComplexPairTy Val, QualType SrcType,
85  QualType DestType, SourceLocation Loc);
86  /// Emit a cast from scalar value Val to DestType.
87  ComplexPairTy EmitScalarToComplexCast(llvm::Value *Val, QualType SrcType,
88  QualType DestType, SourceLocation Loc);
89 
90  //===--------------------------------------------------------------------===//
91  // Visitor Methods
92  //===--------------------------------------------------------------------===//
93 
94  ComplexPairTy Visit(Expr *E) {
95  ApplyDebugLocation DL(CGF, E);
97  }
98 
99  ComplexPairTy VisitStmt(Stmt *S) {
100  S->dump(CGF.getContext().getSourceManager());
101  llvm_unreachable("Stmt can't have complex result type!");
102  }
103  ComplexPairTy VisitExpr(Expr *S);
104  ComplexPairTy VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr());}
105  ComplexPairTy VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
106  return Visit(GE->getResultExpr());
107  }
108  ComplexPairTy VisitImaginaryLiteral(const ImaginaryLiteral *IL);
110  VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE) {
111  return Visit(PE->getReplacement());
112  }
113  ComplexPairTy VisitCoawaitExpr(CoawaitExpr *S) {
114  return CGF.EmitCoawaitExpr(*S).getComplexVal();
115  }
116  ComplexPairTy VisitCoyieldExpr(CoyieldExpr *S) {
117  return CGF.EmitCoyieldExpr(*S).getComplexVal();
118  }
119  ComplexPairTy VisitUnaryCoawait(const UnaryOperator *E) {
120  return Visit(E->getSubExpr());
121  }
122 
123  ComplexPairTy emitConstant(const CodeGenFunction::ConstantEmission &Constant,
124  Expr *E) {
125  assert(Constant && "not a constant");
126  if (Constant.isReference())
127  return EmitLoadOfLValue(Constant.getReferenceLValue(CGF, E),
128  E->getExprLoc());
129 
130  llvm::Constant *pair = Constant.getValue();
131  return ComplexPairTy(pair->getAggregateElement(0U),
132  pair->getAggregateElement(1U));
133  }
134 
135  // l-values.
136  ComplexPairTy VisitDeclRefExpr(DeclRefExpr *E) {
137  if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E))
138  return emitConstant(Constant, E);
139  return EmitLoadOfLValue(E);
140  }
141  ComplexPairTy VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
142  return EmitLoadOfLValue(E);
143  }
144  ComplexPairTy VisitObjCMessageExpr(ObjCMessageExpr *E) {
145  return CGF.EmitObjCMessageExpr(E).getComplexVal();
146  }
147  ComplexPairTy VisitArraySubscriptExpr(Expr *E) { return EmitLoadOfLValue(E); }
148  ComplexPairTy VisitMemberExpr(MemberExpr *ME) {
149  if (CodeGenFunction::ConstantEmission Constant =
150  CGF.tryEmitAsConstant(ME)) {
151  CGF.EmitIgnoredExpr(ME->getBase());
152  return emitConstant(Constant, ME);
153  }
154  return EmitLoadOfLValue(ME);
155  }
156  ComplexPairTy VisitOpaqueValueExpr(OpaqueValueExpr *E) {
157  if (E->isGLValue())
158  return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E), E->getExprLoc());
159  return CGF.getOpaqueRValueMapping(E).getComplexVal();
160  }
161 
162  ComplexPairTy VisitPseudoObjectExpr(PseudoObjectExpr *E) {
163  return CGF.EmitPseudoObjectRValue(E).getComplexVal();
164  }
165 
166  // FIXME: CompoundLiteralExpr
167 
168  ComplexPairTy EmitCast(CastKind CK, Expr *Op, QualType DestTy);
169  ComplexPairTy VisitImplicitCastExpr(ImplicitCastExpr *E) {
170  // Unlike for scalars, we don't have to worry about function->ptr demotion
171  // here.
172  return EmitCast(E->getCastKind(), E->getSubExpr(), E->getType());
173  }
174  ComplexPairTy VisitCastExpr(CastExpr *E) {
175  if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
176  CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
177  return EmitCast(E->getCastKind(), E->getSubExpr(), E->getType());
178  }
179  ComplexPairTy VisitCallExpr(const CallExpr *E);
180  ComplexPairTy VisitStmtExpr(const StmtExpr *E);
181 
182  // Operators.
183  ComplexPairTy VisitPrePostIncDec(const UnaryOperator *E,
184  bool isInc, bool isPre) {
185  LValue LV = CGF.EmitLValue(E->getSubExpr());
186  return CGF.EmitComplexPrePostIncDec(E, LV, isInc, isPre);
187  }
188  ComplexPairTy VisitUnaryPostDec(const UnaryOperator *E) {
189  return VisitPrePostIncDec(E, false, false);
190  }
191  ComplexPairTy VisitUnaryPostInc(const UnaryOperator *E) {
192  return VisitPrePostIncDec(E, true, false);
193  }
194  ComplexPairTy VisitUnaryPreDec(const UnaryOperator *E) {
195  return VisitPrePostIncDec(E, false, true);
196  }
197  ComplexPairTy VisitUnaryPreInc(const UnaryOperator *E) {
198  return VisitPrePostIncDec(E, true, true);
199  }
200  ComplexPairTy VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
201  ComplexPairTy VisitUnaryPlus (const UnaryOperator *E) {
202  TestAndClearIgnoreReal();
203  TestAndClearIgnoreImag();
204  return Visit(E->getSubExpr());
205  }
206  ComplexPairTy VisitUnaryMinus (const UnaryOperator *E);
207  ComplexPairTy VisitUnaryNot (const UnaryOperator *E);
208  // LNot,Real,Imag never return complex.
209  ComplexPairTy VisitUnaryExtension(const UnaryOperator *E) {
210  return Visit(E->getSubExpr());
211  }
212  ComplexPairTy VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
213  return Visit(DAE->getExpr());
214  }
215  ComplexPairTy VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
217  return Visit(DIE->getExpr());
218  }
219  ComplexPairTy VisitExprWithCleanups(ExprWithCleanups *E) {
220  CGF.enterFullExpression(E);
222  ComplexPairTy Vals = Visit(E->getSubExpr());
223  // Defend against dominance problems caused by jumps out of expression
224  // evaluation through the shared cleanup block.
225  Scope.ForceCleanup({&Vals.first, &Vals.second});
226  return Vals;
227  }
228  ComplexPairTy VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
229  assert(E->getType()->isAnyComplexType() && "Expected complex type!");
230  QualType Elem = E->getType()->castAs<ComplexType>()->getElementType();
231  llvm::Constant *Null = llvm::Constant::getNullValue(CGF.ConvertType(Elem));
232  return ComplexPairTy(Null, Null);
233  }
234  ComplexPairTy VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
235  assert(E->getType()->isAnyComplexType() && "Expected complex type!");
236  QualType Elem = E->getType()->castAs<ComplexType>()->getElementType();
237  llvm::Constant *Null =
238  llvm::Constant::getNullValue(CGF.ConvertType(Elem));
239  return ComplexPairTy(Null, Null);
240  }
241 
242  struct BinOpInfo {
243  ComplexPairTy LHS;
244  ComplexPairTy RHS;
245  QualType Ty; // Computation Type.
246  };
247 
248  BinOpInfo EmitBinOps(const BinaryOperator *E);
249  LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
250  ComplexPairTy (ComplexExprEmitter::*Func)
251  (const BinOpInfo &),
252  RValue &Val);
253  ComplexPairTy EmitCompoundAssign(const CompoundAssignOperator *E,
254  ComplexPairTy (ComplexExprEmitter::*Func)
255  (const BinOpInfo &));
256 
257  ComplexPairTy EmitBinAdd(const BinOpInfo &Op);
258  ComplexPairTy EmitBinSub(const BinOpInfo &Op);
259  ComplexPairTy EmitBinMul(const BinOpInfo &Op);
260  ComplexPairTy EmitBinDiv(const BinOpInfo &Op);
261 
262  ComplexPairTy EmitComplexBinOpLibCall(StringRef LibCallName,
263  const BinOpInfo &Op);
264 
265  ComplexPairTy VisitBinAdd(const BinaryOperator *E) {
266  return EmitBinAdd(EmitBinOps(E));
267  }
268  ComplexPairTy VisitBinSub(const BinaryOperator *E) {
269  return EmitBinSub(EmitBinOps(E));
270  }
271  ComplexPairTy VisitBinMul(const BinaryOperator *E) {
272  return EmitBinMul(EmitBinOps(E));
273  }
274  ComplexPairTy VisitBinDiv(const BinaryOperator *E) {
275  return EmitBinDiv(EmitBinOps(E));
276  }
277 
278  // Compound assignments.
279  ComplexPairTy VisitBinAddAssign(const CompoundAssignOperator *E) {
280  return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinAdd);
281  }
282  ComplexPairTy VisitBinSubAssign(const CompoundAssignOperator *E) {
283  return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinSub);
284  }
285  ComplexPairTy VisitBinMulAssign(const CompoundAssignOperator *E) {
286  return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinMul);
287  }
288  ComplexPairTy VisitBinDivAssign(const CompoundAssignOperator *E) {
289  return EmitCompoundAssign(E, &ComplexExprEmitter::EmitBinDiv);
290  }
291 
292  // GCC rejects rem/and/or/xor for integer complex.
293  // Logical and/or always return int, never complex.
294 
295  // No comparisons produce a complex result.
296 
297  LValue EmitBinAssignLValue(const BinaryOperator *E,
298  ComplexPairTy &Val);
299  ComplexPairTy VisitBinAssign (const BinaryOperator *E);
300  ComplexPairTy VisitBinComma (const BinaryOperator *E);
301 
302 
304  VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
305  ComplexPairTy VisitChooseExpr(ChooseExpr *CE);
306 
307  ComplexPairTy VisitInitListExpr(InitListExpr *E);
308 
309  ComplexPairTy VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
310  return EmitLoadOfLValue(E);
311  }
312 
313  ComplexPairTy VisitVAArgExpr(VAArgExpr *E);
314 
315  ComplexPairTy VisitAtomicExpr(AtomicExpr *E) {
316  return CGF.EmitAtomicExpr(E).getComplexVal();
317  }
318 };
319 } // end anonymous namespace.
320 
321 //===----------------------------------------------------------------------===//
322 // Utilities
323 //===----------------------------------------------------------------------===//
324 
327  CharUnits offset = CharUnits::Zero();
328  return Builder.CreateStructGEP(addr, 0, offset, addr.getName() + ".realp");
329 }
330 
333  QualType eltType = complexType->castAs<ComplexType>()->getElementType();
334  CharUnits offset = getContext().getTypeSizeInChars(eltType);
335  return Builder.CreateStructGEP(addr, 1, offset, 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_ZeroToOCLEvent:
508  case CK_ZeroToOCLQueue:
509  case CK_AddressSpaceConversion:
510  case CK_IntToOCLSampler:
511  llvm_unreachable("invalid cast kind for complex value");
512 
513  case CK_FloatingRealToComplex:
514  case CK_IntegralRealToComplex:
515  return EmitScalarToComplexCast(CGF.EmitScalarExpr(Op), Op->getType(),
516  DestTy, Op->getExprLoc());
517 
518  case CK_FloatingComplexCast:
519  case CK_FloatingComplexToIntegralComplex:
520  case CK_IntegralComplexCast:
521  case CK_IntegralComplexToFloatingComplex:
522  return EmitComplexToComplexCast(Visit(Op), Op->getType(), DestTy,
523  Op->getExprLoc());
524  }
525 
526  llvm_unreachable("unknown cast resulting in complex value");
527 }
528 
529 ComplexPairTy ComplexExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
530  TestAndClearIgnoreReal();
531  TestAndClearIgnoreImag();
532  ComplexPairTy Op = Visit(E->getSubExpr());
533 
534  llvm::Value *ResR, *ResI;
535  if (Op.first->getType()->isFloatingPointTy()) {
536  ResR = Builder.CreateFNeg(Op.first, "neg.r");
537  ResI = Builder.CreateFNeg(Op.second, "neg.i");
538  } else {
539  ResR = Builder.CreateNeg(Op.first, "neg.r");
540  ResI = Builder.CreateNeg(Op.second, "neg.i");
541  }
542  return ComplexPairTy(ResR, ResI);
543 }
544 
545 ComplexPairTy ComplexExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
546  TestAndClearIgnoreReal();
547  TestAndClearIgnoreImag();
548  // ~(a+ib) = a + i*-b
549  ComplexPairTy Op = Visit(E->getSubExpr());
550  llvm::Value *ResI;
551  if (Op.second->getType()->isFloatingPointTy())
552  ResI = Builder.CreateFNeg(Op.second, "conj.i");
553  else
554  ResI = Builder.CreateNeg(Op.second, "conj.i");
555 
556  return ComplexPairTy(Op.first, ResI);
557 }
558 
559 ComplexPairTy ComplexExprEmitter::EmitBinAdd(const BinOpInfo &Op) {
560  llvm::Value *ResR, *ResI;
561 
562  if (Op.LHS.first->getType()->isFloatingPointTy()) {
563  ResR = Builder.CreateFAdd(Op.LHS.first, Op.RHS.first, "add.r");
564  if (Op.LHS.second && Op.RHS.second)
565  ResI = Builder.CreateFAdd(Op.LHS.second, Op.RHS.second, "add.i");
566  else
567  ResI = Op.LHS.second ? Op.LHS.second : Op.RHS.second;
568  assert(ResI && "Only one operand may be real!");
569  } else {
570  ResR = Builder.CreateAdd(Op.LHS.first, Op.RHS.first, "add.r");
571  assert(Op.LHS.second && Op.RHS.second &&
572  "Both operands of integer complex operators must be complex!");
573  ResI = Builder.CreateAdd(Op.LHS.second, Op.RHS.second, "add.i");
574  }
575  return ComplexPairTy(ResR, ResI);
576 }
577 
578 ComplexPairTy ComplexExprEmitter::EmitBinSub(const BinOpInfo &Op) {
579  llvm::Value *ResR, *ResI;
580  if (Op.LHS.first->getType()->isFloatingPointTy()) {
581  ResR = Builder.CreateFSub(Op.LHS.first, Op.RHS.first, "sub.r");
582  if (Op.LHS.second && Op.RHS.second)
583  ResI = Builder.CreateFSub(Op.LHS.second, Op.RHS.second, "sub.i");
584  else
585  ResI = Op.LHS.second ? Op.LHS.second
586  : Builder.CreateFNeg(Op.RHS.second, "sub.i");
587  assert(ResI && "Only one operand may be real!");
588  } else {
589  ResR = Builder.CreateSub(Op.LHS.first, Op.RHS.first, "sub.r");
590  assert(Op.LHS.second && Op.RHS.second &&
591  "Both operands of integer complex operators must be complex!");
592  ResI = Builder.CreateSub(Op.LHS.second, Op.RHS.second, "sub.i");
593  }
594  return ComplexPairTy(ResR, ResI);
595 }
596 
597 /// \brief Emit a libcall for a binary operation on complex types.
598 ComplexPairTy ComplexExprEmitter::EmitComplexBinOpLibCall(StringRef LibCallName,
599  const BinOpInfo &Op) {
600  CallArgList Args;
601  Args.add(RValue::get(Op.LHS.first),
602  Op.Ty->castAs<ComplexType>()->getElementType());
603  Args.add(RValue::get(Op.LHS.second),
604  Op.Ty->castAs<ComplexType>()->getElementType());
605  Args.add(RValue::get(Op.RHS.first),
606  Op.Ty->castAs<ComplexType>()->getElementType());
607  Args.add(RValue::get(Op.RHS.second),
608  Op.Ty->castAs<ComplexType>()->getElementType());
609 
610  // We *must* use the full CG function call building logic here because the
611  // complex type has special ABI handling. We also should not forget about
612  // special calling convention which may be used for compiler builtins.
613 
614  // We create a function qualified type to state that this call does not have
615  // any exceptions.
617  EPI = EPI.withExceptionSpec(
619  SmallVector<QualType, 4> ArgsQTys(
620  4, Op.Ty->castAs<ComplexType>()->getElementType());
621  QualType FQTy = CGF.getContext().getFunctionType(Op.Ty, ArgsQTys, EPI);
622  const CGFunctionInfo &FuncInfo = CGF.CGM.getTypes().arrangeFreeFunctionCall(
623  Args, cast<FunctionType>(FQTy.getTypePtr()), false);
624 
625  llvm::FunctionType *FTy = CGF.CGM.getTypes().GetFunctionType(FuncInfo);
626  llvm::Constant *Func = CGF.CGM.CreateBuiltinFunction(FTy, LibCallName);
627  CGCallee Callee = CGCallee::forDirect(Func, FQTy->getAs<FunctionProtoType>());
628 
629  llvm::Instruction *Call;
630  RValue Res = CGF.EmitCall(FuncInfo, Callee, ReturnValueSlot(), Args, &Call);
631  cast<llvm::CallInst>(Call)->setCallingConv(CGF.CGM.getBuiltinCC());
632  return Res.getComplexVal();
633 }
634 
635 /// \brief Lookup the libcall name for a given floating point type complex
636 /// multiply.
638  switch (Ty->getTypeID()) {
639  default:
640  llvm_unreachable("Unsupported floating point type!");
641  case llvm::Type::HalfTyID:
642  return "__mulhc3";
643  case llvm::Type::FloatTyID:
644  return "__mulsc3";
645  case llvm::Type::DoubleTyID:
646  return "__muldc3";
647  case llvm::Type::PPC_FP128TyID:
648  return "__multc3";
649  case llvm::Type::X86_FP80TyID:
650  return "__mulxc3";
651  case llvm::Type::FP128TyID:
652  return "__multc3";
653  }
654 }
655 
656 // See C11 Annex G.5.1 for the semantics of multiplicative operators on complex
657 // typed values.
658 ComplexPairTy ComplexExprEmitter::EmitBinMul(const BinOpInfo &Op) {
659  using llvm::Value;
660  Value *ResR, *ResI;
661  llvm::MDBuilder MDHelper(CGF.getLLVMContext());
662 
663  if (Op.LHS.first->getType()->isFloatingPointTy()) {
664  // The general formulation is:
665  // (a + ib) * (c + id) = (a * c - b * d) + i(a * d + b * c)
666  //
667  // But we can fold away components which would be zero due to a real
668  // operand according to C11 Annex G.5.1p2.
669  // FIXME: C11 also provides for imaginary types which would allow folding
670  // still more of this within the type system.
671 
672  if (Op.LHS.second && Op.RHS.second) {
673  // If both operands are complex, emit the core math directly, and then
674  // test for NaNs. If we find NaNs in the result, we delegate to a libcall
675  // to carefully re-compute the correct infinity representation if
676  // possible. The expectation is that the presence of NaNs here is
677  // *extremely* rare, and so the cost of the libcall is almost irrelevant.
678  // This is good, because the libcall re-computes the core multiplication
679  // exactly the same as we do here and re-tests for NaNs in order to be
680  // a generic complex*complex libcall.
681 
682  // First compute the four products.
683  Value *AC = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul_ac");
684  Value *BD = Builder.CreateFMul(Op.LHS.second, Op.RHS.second, "mul_bd");
685  Value *AD = Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul_ad");
686  Value *BC = Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul_bc");
687 
688  // The real part is the difference of the first two, the imaginary part is
689  // the sum of the second.
690  ResR = Builder.CreateFSub(AC, BD, "mul_r");
691  ResI = Builder.CreateFAdd(AD, BC, "mul_i");
692 
693  // Emit the test for the real part becoming NaN and create a branch to
694  // handle it. We test for NaN by comparing the number to itself.
695  Value *IsRNaN = Builder.CreateFCmpUNO(ResR, ResR, "isnan_cmp");
696  llvm::BasicBlock *ContBB = CGF.createBasicBlock("complex_mul_cont");
697  llvm::BasicBlock *INaNBB = CGF.createBasicBlock("complex_mul_imag_nan");
698  llvm::Instruction *Branch = Builder.CreateCondBr(IsRNaN, INaNBB, ContBB);
699  llvm::BasicBlock *OrigBB = Branch->getParent();
700 
701  // Give hint that we very much don't expect to see NaNs.
702  // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
703  llvm::MDNode *BrWeight = MDHelper.createBranchWeights(1, (1U << 20) - 1);
704  Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);
705 
706  // Now test the imaginary part and create its branch.
707  CGF.EmitBlock(INaNBB);
708  Value *IsINaN = Builder.CreateFCmpUNO(ResI, ResI, "isnan_cmp");
709  llvm::BasicBlock *LibCallBB = CGF.createBasicBlock("complex_mul_libcall");
710  Branch = Builder.CreateCondBr(IsINaN, LibCallBB, ContBB);
711  Branch->setMetadata(llvm::LLVMContext::MD_prof, BrWeight);
712 
713  // Now emit the libcall on this slowest of the slow paths.
714  CGF.EmitBlock(LibCallBB);
715  Value *LibCallR, *LibCallI;
716  std::tie(LibCallR, LibCallI) = EmitComplexBinOpLibCall(
717  getComplexMultiplyLibCallName(Op.LHS.first->getType()), Op);
718  Builder.CreateBr(ContBB);
719 
720  // Finally continue execution by phi-ing together the different
721  // computation paths.
722  CGF.EmitBlock(ContBB);
723  llvm::PHINode *RealPHI = Builder.CreatePHI(ResR->getType(), 3, "real_mul_phi");
724  RealPHI->addIncoming(ResR, OrigBB);
725  RealPHI->addIncoming(ResR, INaNBB);
726  RealPHI->addIncoming(LibCallR, LibCallBB);
727  llvm::PHINode *ImagPHI = Builder.CreatePHI(ResI->getType(), 3, "imag_mul_phi");
728  ImagPHI->addIncoming(ResI, OrigBB);
729  ImagPHI->addIncoming(ResI, INaNBB);
730  ImagPHI->addIncoming(LibCallI, LibCallBB);
731  return ComplexPairTy(RealPHI, ImagPHI);
732  }
733  assert((Op.LHS.second || Op.RHS.second) &&
734  "At least one operand must be complex!");
735 
736  // If either of the operands is a real rather than a complex, the
737  // imaginary component is ignored when computing the real component of the
738  // result.
739  ResR = Builder.CreateFMul(Op.LHS.first, Op.RHS.first, "mul.rl");
740 
741  ResI = Op.LHS.second
742  ? Builder.CreateFMul(Op.LHS.second, Op.RHS.first, "mul.il")
743  : Builder.CreateFMul(Op.LHS.first, Op.RHS.second, "mul.ir");
744  } else {
745  assert(Op.LHS.second && Op.RHS.second &&
746  "Both operands of integer complex operators must be complex!");
747  Value *ResRl = Builder.CreateMul(Op.LHS.first, Op.RHS.first, "mul.rl");
748  Value *ResRr = Builder.CreateMul(Op.LHS.second, Op.RHS.second, "mul.rr");
749  ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
750 
751  Value *ResIl = Builder.CreateMul(Op.LHS.second, Op.RHS.first, "mul.il");
752  Value *ResIr = Builder.CreateMul(Op.LHS.first, Op.RHS.second, "mul.ir");
753  ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
754  }
755  return ComplexPairTy(ResR, ResI);
756 }
757 
758 // See C11 Annex G.5.1 for the semantics of multiplicative operators on complex
759 // typed values.
760 ComplexPairTy ComplexExprEmitter::EmitBinDiv(const BinOpInfo &Op) {
761  llvm::Value *LHSr = Op.LHS.first, *LHSi = Op.LHS.second;
762  llvm::Value *RHSr = Op.RHS.first, *RHSi = Op.RHS.second;
763 
764 
765  llvm::Value *DSTr, *DSTi;
766  if (LHSr->getType()->isFloatingPointTy()) {
767  // If we have a complex operand on the RHS, we delegate to a libcall to
768  // handle all of the complexities and minimize underflow/overflow cases.
769  //
770  // FIXME: We would be able to avoid the libcall in many places if we
771  // supported imaginary types in addition to complex types.
772  if (RHSi) {
773  BinOpInfo LibCallOp = Op;
774  // If LHS was a real, supply a null imaginary part.
775  if (!LHSi)
776  LibCallOp.LHS.second = llvm::Constant::getNullValue(LHSr->getType());
777 
778  switch (LHSr->getType()->getTypeID()) {
779  default:
780  llvm_unreachable("Unsupported floating point type!");
781  case llvm::Type::HalfTyID:
782  return EmitComplexBinOpLibCall("__divhc3", LibCallOp);
783  case llvm::Type::FloatTyID:
784  return EmitComplexBinOpLibCall("__divsc3", LibCallOp);
785  case llvm::Type::DoubleTyID:
786  return EmitComplexBinOpLibCall("__divdc3", LibCallOp);
787  case llvm::Type::PPC_FP128TyID:
788  return EmitComplexBinOpLibCall("__divtc3", LibCallOp);
789  case llvm::Type::X86_FP80TyID:
790  return EmitComplexBinOpLibCall("__divxc3", LibCallOp);
791  case llvm::Type::FP128TyID:
792  return EmitComplexBinOpLibCall("__divtc3", LibCallOp);
793  }
794  }
795  assert(LHSi && "Can have at most one non-complex operand!");
796 
797  DSTr = Builder.CreateFDiv(LHSr, RHSr);
798  DSTi = Builder.CreateFDiv(LHSi, RHSr);
799  } else {
800  assert(Op.LHS.second && Op.RHS.second &&
801  "Both operands of integer complex operators must be complex!");
802  // (a+ib) / (c+id) = ((ac+bd)/(cc+dd)) + i((bc-ad)/(cc+dd))
803  llvm::Value *Tmp1 = Builder.CreateMul(LHSr, RHSr); // a*c
804  llvm::Value *Tmp2 = Builder.CreateMul(LHSi, RHSi); // b*d
805  llvm::Value *Tmp3 = Builder.CreateAdd(Tmp1, Tmp2); // ac+bd
806 
807  llvm::Value *Tmp4 = Builder.CreateMul(RHSr, RHSr); // c*c
808  llvm::Value *Tmp5 = Builder.CreateMul(RHSi, RHSi); // d*d
809  llvm::Value *Tmp6 = Builder.CreateAdd(Tmp4, Tmp5); // cc+dd
810 
811  llvm::Value *Tmp7 = Builder.CreateMul(LHSi, RHSr); // b*c
812  llvm::Value *Tmp8 = Builder.CreateMul(LHSr, RHSi); // a*d
813  llvm::Value *Tmp9 = Builder.CreateSub(Tmp7, Tmp8); // bc-ad
814 
815  if (Op.Ty->castAs<ComplexType>()->getElementType()->isUnsignedIntegerType()) {
816  DSTr = Builder.CreateUDiv(Tmp3, Tmp6);
817  DSTi = Builder.CreateUDiv(Tmp9, Tmp6);
818  } else {
819  DSTr = Builder.CreateSDiv(Tmp3, Tmp6);
820  DSTi = Builder.CreateSDiv(Tmp9, Tmp6);
821  }
822  }
823 
824  return ComplexPairTy(DSTr, DSTi);
825 }
826 
827 ComplexExprEmitter::BinOpInfo
828 ComplexExprEmitter::EmitBinOps(const BinaryOperator *E) {
829  TestAndClearIgnoreReal();
830  TestAndClearIgnoreImag();
831  BinOpInfo Ops;
832  if (E->getLHS()->getType()->isRealFloatingType())
833  Ops.LHS = ComplexPairTy(CGF.EmitScalarExpr(E->getLHS()), nullptr);
834  else
835  Ops.LHS = Visit(E->getLHS());
836  if (E->getRHS()->getType()->isRealFloatingType())
837  Ops.RHS = ComplexPairTy(CGF.EmitScalarExpr(E->getRHS()), nullptr);
838  else
839  Ops.RHS = Visit(E->getRHS());
840 
841  Ops.Ty = E->getType();
842  return Ops;
843 }
844 
845 
846 LValue ComplexExprEmitter::
847 EmitCompoundAssignLValue(const CompoundAssignOperator *E,
848  ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo&),
849  RValue &Val) {
850  TestAndClearIgnoreReal();
851  TestAndClearIgnoreImag();
852  QualType LHSTy = E->getLHS()->getType();
853  if (const AtomicType *AT = LHSTy->getAs<AtomicType>())
854  LHSTy = AT->getValueType();
855 
856  BinOpInfo OpInfo;
857 
858  // Load the RHS and LHS operands.
859  // __block variables need to have the rhs evaluated first, plus this should
860  // improve codegen a little.
861  OpInfo.Ty = E->getComputationResultType();
862  QualType ComplexElementTy = cast<ComplexType>(OpInfo.Ty)->getElementType();
863 
864  // The RHS should have been converted to the computation type.
865  if (E->getRHS()->getType()->isRealFloatingType()) {
866  assert(
867  CGF.getContext()
868  .hasSameUnqualifiedType(ComplexElementTy, E->getRHS()->getType()));
869  OpInfo.RHS = ComplexPairTy(CGF.EmitScalarExpr(E->getRHS()), nullptr);
870  } else {
871  assert(CGF.getContext()
872  .hasSameUnqualifiedType(OpInfo.Ty, E->getRHS()->getType()));
873  OpInfo.RHS = Visit(E->getRHS());
874  }
875 
876  LValue LHS = CGF.EmitLValue(E->getLHS());
877 
878  // Load from the l-value and convert it.
879  SourceLocation Loc = E->getExprLoc();
880  if (LHSTy->isAnyComplexType()) {
881  ComplexPairTy LHSVal = EmitLoadOfLValue(LHS, Loc);
882  OpInfo.LHS = EmitComplexToComplexCast(LHSVal, LHSTy, OpInfo.Ty, Loc);
883  } else {
884  llvm::Value *LHSVal = CGF.EmitLoadOfScalar(LHS, Loc);
885  // For floating point real operands we can directly pass the scalar form
886  // to the binary operator emission and potentially get more efficient code.
887  if (LHSTy->isRealFloatingType()) {
888  if (!CGF.getContext().hasSameUnqualifiedType(ComplexElementTy, LHSTy))
889  LHSVal = CGF.EmitScalarConversion(LHSVal, LHSTy, ComplexElementTy, Loc);
890  OpInfo.LHS = ComplexPairTy(LHSVal, nullptr);
891  } else {
892  OpInfo.LHS = EmitScalarToComplexCast(LHSVal, LHSTy, OpInfo.Ty, Loc);
893  }
894  }
895 
896  // Expand the binary operator.
897  ComplexPairTy Result = (this->*Func)(OpInfo);
898 
899  // Truncate the result and store it into the LHS lvalue.
900  if (LHSTy->isAnyComplexType()) {
901  ComplexPairTy ResVal =
902  EmitComplexToComplexCast(Result, OpInfo.Ty, LHSTy, Loc);
903  EmitStoreOfComplex(ResVal, LHS, /*isInit*/ false);
904  Val = RValue::getComplex(ResVal);
905  } else {
906  llvm::Value *ResVal =
907  CGF.EmitComplexToScalarConversion(Result, OpInfo.Ty, LHSTy, Loc);
908  CGF.EmitStoreOfScalar(ResVal, LHS, /*isInit*/ false);
909  Val = RValue::get(ResVal);
910  }
911 
912  return LHS;
913 }
914 
915 // Compound assignments.
916 ComplexPairTy ComplexExprEmitter::
917 EmitCompoundAssign(const CompoundAssignOperator *E,
918  ComplexPairTy (ComplexExprEmitter::*Func)(const BinOpInfo&)){
919  RValue Val;
920  LValue LV = EmitCompoundAssignLValue(E, Func, Val);
921 
922  // The result of an assignment in C is the assigned r-value.
923  if (!CGF.getLangOpts().CPlusPlus)
924  return Val.getComplexVal();
925 
926  // If the lvalue is non-volatile, return the computed value of the assignment.
927  if (!LV.isVolatileQualified())
928  return Val.getComplexVal();
929 
930  return EmitLoadOfLValue(LV, E->getExprLoc());
931 }
932 
933 LValue ComplexExprEmitter::EmitBinAssignLValue(const BinaryOperator *E,
934  ComplexPairTy &Val) {
935  assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
936  E->getRHS()->getType()) &&
937  "Invalid assignment");
938  TestAndClearIgnoreReal();
939  TestAndClearIgnoreImag();
940 
941  // Emit the RHS. __block variables need the RHS evaluated first.
942  Val = Visit(E->getRHS());
943 
944  // Compute the address to store into.
945  LValue LHS = CGF.EmitLValue(E->getLHS());
946 
947  // Store the result value into the LHS lvalue.
948  EmitStoreOfComplex(Val, LHS, /*isInit*/ false);
949 
950  return LHS;
951 }
952 
953 ComplexPairTy ComplexExprEmitter::VisitBinAssign(const BinaryOperator *E) {
954  ComplexPairTy Val;
955  LValue LV = EmitBinAssignLValue(E, Val);
956 
957  // The result of an assignment in C is the assigned r-value.
958  if (!CGF.getLangOpts().CPlusPlus)
959  return Val;
960 
961  // If the lvalue is non-volatile, return the computed value of the assignment.
962  if (!LV.isVolatileQualified())
963  return Val;
964 
965  return EmitLoadOfLValue(LV, E->getExprLoc());
966 }
967 
968 ComplexPairTy ComplexExprEmitter::VisitBinComma(const BinaryOperator *E) {
969  CGF.EmitIgnoredExpr(E->getLHS());
970  return Visit(E->getRHS());
971 }
972 
973 ComplexPairTy ComplexExprEmitter::
974 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
975  TestAndClearIgnoreReal();
976  TestAndClearIgnoreImag();
977  llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
978  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
979  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
980 
981  // Bind the common expression if necessary.
982  CodeGenFunction::OpaqueValueMapping binding(CGF, E);
983 
984 
986  CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
987  CGF.getProfileCount(E));
988 
989  eval.begin(CGF);
990  CGF.EmitBlock(LHSBlock);
991  CGF.incrementProfileCounter(E);
992  ComplexPairTy LHS = Visit(E->getTrueExpr());
993  LHSBlock = Builder.GetInsertBlock();
994  CGF.EmitBranch(ContBlock);
995  eval.end(CGF);
996 
997  eval.begin(CGF);
998  CGF.EmitBlock(RHSBlock);
999  ComplexPairTy RHS = Visit(E->getFalseExpr());
1000  RHSBlock = Builder.GetInsertBlock();
1001  CGF.EmitBlock(ContBlock);
1002  eval.end(CGF);
1003 
1004  // Create a PHI node for the real part.
1005  llvm::PHINode *RealPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.r");
1006  RealPN->addIncoming(LHS.first, LHSBlock);
1007  RealPN->addIncoming(RHS.first, RHSBlock);
1008 
1009  // Create a PHI node for the imaginary part.
1010  llvm::PHINode *ImagPN = Builder.CreatePHI(LHS.first->getType(), 2, "cond.i");
1011  ImagPN->addIncoming(LHS.second, LHSBlock);
1012  ImagPN->addIncoming(RHS.second, RHSBlock);
1013 
1014  return ComplexPairTy(RealPN, ImagPN);
1015 }
1016 
1017 ComplexPairTy ComplexExprEmitter::VisitChooseExpr(ChooseExpr *E) {
1018  return Visit(E->getChosenSubExpr());
1019 }
1020 
1021 ComplexPairTy ComplexExprEmitter::VisitInitListExpr(InitListExpr *E) {
1022  bool Ignore = TestAndClearIgnoreReal();
1023  (void)Ignore;
1024  assert (Ignore == false && "init list ignored");
1025  Ignore = TestAndClearIgnoreImag();
1026  (void)Ignore;
1027  assert (Ignore == false && "init list ignored");
1028 
1029  if (E->getNumInits() == 2) {
1030  llvm::Value *Real = CGF.EmitScalarExpr(E->getInit(0));
1031  llvm::Value *Imag = CGF.EmitScalarExpr(E->getInit(1));
1032  return ComplexPairTy(Real, Imag);
1033  } else if (E->getNumInits() == 1) {
1034  return Visit(E->getInit(0));
1035  }
1036 
1037  // Empty init list intializes to null
1038  assert(E->getNumInits() == 0 && "Unexpected number of inits");
1039  QualType Ty = E->getType()->castAs<ComplexType>()->getElementType();
1040  llvm::Type* LTy = CGF.ConvertType(Ty);
1041  llvm::Value* zeroConstant = llvm::Constant::getNullValue(LTy);
1042  return ComplexPairTy(zeroConstant, zeroConstant);
1043 }
1044 
1045 ComplexPairTy ComplexExprEmitter::VisitVAArgExpr(VAArgExpr *E) {
1046  Address ArgValue = Address::invalid();
1047  Address ArgPtr = CGF.EmitVAArg(E, ArgValue);
1048 
1049  if (!ArgPtr.isValid()) {
1050  CGF.ErrorUnsupported(E, "complex va_arg expression");
1051  llvm::Type *EltTy =
1052  CGF.ConvertType(E->getType()->castAs<ComplexType>()->getElementType());
1053  llvm::Value *U = llvm::UndefValue::get(EltTy);
1054  return ComplexPairTy(U, U);
1055  }
1056 
1057  return EmitLoadOfLValue(CGF.MakeAddrLValue(ArgPtr, E->getType()),
1058  E->getExprLoc());
1059 }
1060 
1061 //===----------------------------------------------------------------------===//
1062 // Entry Point into this File
1063 //===----------------------------------------------------------------------===//
1064 
1065 /// EmitComplexExpr - Emit the computation of the specified expression of
1066 /// complex type, ignoring the result.
1068  bool IgnoreImag) {
1069  assert(E && getComplexType(E->getType()) &&
1070  "Invalid complex expression to emit");
1071 
1072  return ComplexExprEmitter(*this, IgnoreReal, IgnoreImag)
1073  .Visit(const_cast<Expr *>(E));
1074 }
1075 
1077  bool isInit) {
1078  assert(E && getComplexType(E->getType()) &&
1079  "Invalid complex expression to emit");
1080  ComplexExprEmitter Emitter(*this);
1081  ComplexPairTy Val = Emitter.Visit(const_cast<Expr*>(E));
1082  Emitter.EmitStoreOfComplex(Val, dest, isInit);
1083 }
1084 
1085 /// EmitStoreOfComplex - Store a complex number into the specified l-value.
1087  bool isInit) {
1088  ComplexExprEmitter(*this).EmitStoreOfComplex(V, dest, isInit);
1089 }
1090 
1091 /// EmitLoadOfComplex - Load a complex number from the specified address.
1093  SourceLocation loc) {
1094  return ComplexExprEmitter(*this).EmitLoadOfLValue(src, loc);
1095 }
1096 
1098  assert(E->getOpcode() == BO_Assign);
1099  ComplexPairTy Val; // ignored
1100  return ComplexExprEmitter(*this).EmitBinAssignLValue(E, Val);
1101 }
1102 
1103 typedef ComplexPairTy (ComplexExprEmitter::*CompoundFunc)(
1104  const ComplexExprEmitter::BinOpInfo &);
1105 
1107  switch (Op) {
1108  case BO_MulAssign: return &ComplexExprEmitter::EmitBinMul;
1109  case BO_DivAssign: return &ComplexExprEmitter::EmitBinDiv;
1110  case BO_SubAssign: return &ComplexExprEmitter::EmitBinSub;
1111  case BO_AddAssign: return &ComplexExprEmitter::EmitBinAdd;
1112  default:
1113  llvm_unreachable("unexpected complex compound assignment");
1114  }
1115 }
1116 
1119  CompoundFunc Op = getComplexOp(E->getOpcode());
1120  RValue Val;
1121  return ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);
1122 }
1123 
1126  llvm::Value *&Result) {
1127  CompoundFunc Op = getComplexOp(E->getOpcode());
1128  RValue Val;
1129  LValue Ret = ComplexExprEmitter(*this).EmitCompoundAssignLValue(E, Op, Val);
1130  Result = Val.getScalarVal();
1131  return Ret;
1132 }
ReturnValueSlot - Contains the address where the return value of a function can be stored...
Definition: CGCall.h:281
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:3705
LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const
LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E)
A (possibly-)qualified type.
Definition: Type.h:653
CompoundStmt * getSubStmt()
Definition: Expr.h:3504
const Expr * getInit(unsigned Init) const
Definition: Expr.h:3920
Stmt - This represents one statement.
Definition: Stmt.h:66
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:1893
Expr * getBase() const
Definition: Expr.h:2477
static StringRef getComplexMultiplyLibCallName(llvm::Type *Ty)
Lookup the libcall name for a given floating point type complex multiply.
Opcode getOpcode() const
Definition: Expr.h:3026
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1665
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 * getResultExpr() const
The generic selection&#39;s result expression.
Definition: Expr.h:4760
const Expr * getSubExpr() const
Definition: Expr.h:1475
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:1840
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:2637
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6307
Extra information about a function prototype.
Definition: Type.h:3389
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:3000
Address emitAddrOfImagComponent(Address complex, QualType complexType)
An object to manage conditionally-evaluated expressions.
LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E, llvm::Value *&Result)
Address getAddress() const
Definition: CGValue.h:324
QualType getComputationResultType() const
Definition: Expr.h:3217
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
bool isVolatileQualified() const
Definition: CGValue.h:255
An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Expr * getSubExpr()
Definition: Expr.h:2761
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:252
Describes an C or C++ initializer list.
Definition: Expr.h:3872
Address emitAddrOfRealComponent(Address complex, QualType complexType)
BinaryOperatorKind
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2985
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:39
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2710
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:249
ComplexPairTy(ComplexExprEmitter::* CompoundFunc)(const ComplexExprEmitter::BinOpInfo &)
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1042
const Expr * getExpr() const
Get the initialization expression that will be used.
Definition: ExprCXX.h:1141
bool isValid() const
Definition: Address.h:36
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3270
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:39
Represents a call to the builtin function __builtin_va_arg.
Definition: Expr.h:3778
An expression "T()" which creates a value-initialized rvalue of type T, which is a non-class type...
Definition: ExprCXX.h:1802
QualType getElementType() const
Definition: Type.h:2238
Expr - This represents one expression.
Definition: Expr.h:106
static Address invalid()
Definition: Address.h:35
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:66
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6370
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:125
unsigned getNumInits() const
Definition: Expr.h:3902
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &O)
Definition: Type.h:3404
bool isAnyComplexType() const
Definition: Type.h:6025
void add(RValue rvalue, QualType type, bool needscopy=false)
Definition: CGCall.h:207
QualType getType() const
Definition: Expr.h:128
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:903
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:1717
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:3838
const Expr * getSubExpr() const
Definition: Expr.h:1681
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1...
Definition: Expr.h:1463
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:868
QualType getCanonicalType() const
Definition: Type.h:5759
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:4969
Encodes a location in the source.
Expr * getSubExpr() const
Definition: Expr.h:1744
CastKind getCastKind() const
Definition: Expr.h:2757
A scoped helper to set the current debug location to the specified location or preferred location of ...
Definition: CGDebugInfo.h:620
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:186
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:5103
An aligned address.
Definition: Address.h:25
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2822
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:3488
QualType getType() const
Definition: CGValue.h:261
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:216
Expr * getLHS() const
Definition: Expr.h:3029
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:3191
Represents a C11 generic selection.
Definition: Expr.h:4684
CGFunctionInfo - Class to encapsulate the information about a function definition.
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:905
Dataflow Directional Tag Classes.
static CompoundFunc getComplexOp(BinaryOperatorKind Op)
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition: CGValue.h:93
CodeGenFunction::ComplexPairTy ComplexPairTy
Represents a &#39;co_yield&#39; expression.
Definition: ExprCXX.h:4387
const Expr * getExpr() const
Definition: ExprCXX.h:1077
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition: Expr.cpp:1307
Complex values, per C99 6.2.5p11.
Definition: Type.h:2225
void dump() const
Dumps the specified AST fragment and all subtrees to llvm::errs().
Definition: ASTDumper.cpp:2732
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition: Expr.h:3227
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
bool isAtomicType() const
Definition: Type.h:6054
Represents a &#39;co_await&#39; expression.
Definition: ExprCXX.h:4304
llvm::StringRef getName() const
Return the IR name of the pointer value.
Definition: Address.h:62
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3022
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:513
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1113
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2387
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:3664
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2209
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:956
static RValue get(llvm::Value *V)
Definition: CGValue.h:86
Expr * getRHS() const
Definition: Expr.h:3031
LValue - This represents an lvalue references.
Definition: CGValue.h:167
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:182
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:4580