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