1 //===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Frontend/CodeGenOptions.h"
15 #include "CodeGenFunction.h"
17 #include "CGObjCRuntime.h"
18 #include "CodeGenModule.h"
19 #include "CGDebugInfo.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/StmtVisitor.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "llvm/Constants.h"
26 #include "llvm/Function.h"
27 #include "llvm/GlobalVariable.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Module.h"
30 #include "llvm/Support/CFG.h"
31 #include "llvm/Target/TargetData.h"
34 using namespace clang;
35 using namespace CodeGen;
38 //===----------------------------------------------------------------------===//
39 // Scalar Expression Emitter
40 //===----------------------------------------------------------------------===//
46 QualType Ty; // Computation Type.
47 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
48 const Expr *E; // Entire expr, for error unsupported. May not be binop.
51 static bool MustVisitNullValue(const Expr *E) {
52 // If a null pointer expression's type is the C++0x nullptr_t, then
53 // it's not necessarily a simple constant and it must be evaluated
54 // for its potential side effects.
55 return E->getType()->isNullPtrType();
58 class ScalarExprEmitter
59 : public StmtVisitor<ScalarExprEmitter, Value*> {
62 bool IgnoreResultAssign;
63 llvm::LLVMContext &VMContext;
66 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
67 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
68 VMContext(cgf.getLLVMContext()) {
71 //===--------------------------------------------------------------------===//
73 //===--------------------------------------------------------------------===//
75 bool TestAndClearIgnoreResultAssign() {
76 bool I = IgnoreResultAssign;
77 IgnoreResultAssign = false;
81 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
82 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
83 LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); }
85 Value *EmitLoadOfLValue(LValue LV) {
86 return CGF.EmitLoadOfLValue(LV).getScalarVal();
89 /// EmitLoadOfLValue - Given an expression with complex type that represents a
90 /// value l-value, this method emits the address of the l-value, then loads
91 /// and returns the result.
92 Value *EmitLoadOfLValue(const Expr *E) {
93 return EmitLoadOfLValue(EmitCheckedLValue(E));
96 /// EmitConversionToBool - Convert the specified expression value to a
97 /// boolean (i1) truth value. This is equivalent to "Val != 0".
98 Value *EmitConversionToBool(Value *Src, QualType DstTy);
100 /// EmitScalarConversion - Emit a conversion from the specified type to the
101 /// specified destination type, both of which are LLVM scalar types.
102 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
104 /// EmitComplexToScalarConversion - Emit a conversion from the specified
105 /// complex type to the specified destination type, where the destination type
106 /// is an LLVM scalar type.
107 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
108 QualType SrcTy, QualType DstTy);
110 /// EmitNullValue - Emit a value that corresponds to null for the given type.
111 Value *EmitNullValue(QualType Ty);
113 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
114 Value *EmitFloatToBoolConversion(Value *V) {
115 // Compare against 0.0 for fp scalars.
116 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
117 return Builder.CreateFCmpUNE(V, Zero, "tobool");
120 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
121 Value *EmitPointerToBoolConversion(Value *V) {
122 Value *Zero = llvm::ConstantPointerNull::get(
123 cast<llvm::PointerType>(V->getType()));
124 return Builder.CreateICmpNE(V, Zero, "tobool");
127 Value *EmitIntToBoolConversion(Value *V) {
128 // Because of the type rules of C, we often end up computing a
129 // logical value, then zero extending it to int, then wanting it
130 // as a logical value again. Optimize this common case.
131 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
132 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
133 Value *Result = ZI->getOperand(0);
134 // If there aren't any more uses, zap the instruction to save space.
135 // Note that there can be more uses, for example if this
136 // is the result of an assignment.
138 ZI->eraseFromParent();
143 return Builder.CreateIsNotNull(V, "tobool");
146 //===--------------------------------------------------------------------===//
148 //===--------------------------------------------------------------------===//
150 Value *Visit(Expr *E) {
151 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
154 Value *VisitStmt(Stmt *S) {
155 S->dump(CGF.getContext().getSourceManager());
156 llvm_unreachable("Stmt can't have complex result type!");
158 Value *VisitExpr(Expr *S);
160 Value *VisitParenExpr(ParenExpr *PE) {
161 return Visit(PE->getSubExpr());
163 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
164 return Visit(E->getReplacement());
166 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
167 return Visit(GE->getResultExpr());
171 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
172 return Builder.getInt(E->getValue());
174 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
175 return llvm::ConstantFP::get(VMContext, E->getValue());
177 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
178 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
180 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
181 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
183 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
184 return EmitNullValue(E->getType());
186 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
187 return EmitNullValue(E->getType());
189 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
190 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
191 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
192 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
193 return Builder.CreateBitCast(V, ConvertType(E->getType()));
196 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
197 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
200 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
202 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
204 // Otherwise, assume the mapping is the scalar directly.
205 return CGF.getOpaqueRValueMapping(E).getScalarVal();
209 Value *VisitDeclRefExpr(DeclRefExpr *E) {
210 Expr::EvalResult Result;
211 if (!E->Evaluate(Result, CGF.getContext()))
212 return EmitLoadOfLValue(E);
214 assert(!Result.HasSideEffects && "Constant declref with side-effect?!");
217 if (Result.Val.isInt())
218 C = Builder.getInt(Result.Val.getInt());
219 else if (Result.Val.isFloat())
220 C = llvm::ConstantFP::get(VMContext, Result.Val.getFloat());
222 return EmitLoadOfLValue(E);
224 // Make sure we emit a debug reference to the global variable.
225 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
226 if (!CGF.getContext().DeclMustBeEmitted(VD))
227 CGF.EmitDeclRefExprDbgValue(E, C);
228 } else if (isa<EnumConstantDecl>(E->getDecl())) {
229 CGF.EmitDeclRefExprDbgValue(E, C);
234 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
235 return CGF.EmitObjCSelectorExpr(E);
237 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
238 return CGF.EmitObjCProtocolExpr(E);
240 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
241 return EmitLoadOfLValue(E);
243 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
244 assert(E->getObjectKind() == OK_Ordinary &&
245 "reached property reference without lvalue-to-rvalue");
246 return EmitLoadOfLValue(E);
248 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
249 if (E->getMethodDecl() &&
250 E->getMethodDecl()->getResultType()->isReferenceType())
251 return EmitLoadOfLValue(E);
252 return CGF.EmitObjCMessageExpr(E).getScalarVal();
255 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
256 LValue LV = CGF.EmitObjCIsaExpr(E);
257 Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
261 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
262 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
263 Value *VisitMemberExpr(MemberExpr *E);
264 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
265 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
266 return EmitLoadOfLValue(E);
269 Value *VisitInitListExpr(InitListExpr *E);
271 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
272 return CGF.CGM.EmitNullConstant(E->getType());
274 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
275 if (E->getType()->isVariablyModifiedType())
276 CGF.EmitVariablyModifiedType(E->getType());
277 return VisitCastExpr(E);
279 Value *VisitCastExpr(CastExpr *E);
281 Value *VisitCallExpr(const CallExpr *E) {
282 if (E->getCallReturnType()->isReferenceType())
283 return EmitLoadOfLValue(E);
285 return CGF.EmitCallExpr(E).getScalarVal();
288 Value *VisitStmtExpr(const StmtExpr *E);
290 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
293 Value *VisitUnaryPostDec(const UnaryOperator *E) {
294 LValue LV = EmitLValue(E->getSubExpr());
295 return EmitScalarPrePostIncDec(E, LV, false, false);
297 Value *VisitUnaryPostInc(const UnaryOperator *E) {
298 LValue LV = EmitLValue(E->getSubExpr());
299 return EmitScalarPrePostIncDec(E, LV, true, false);
301 Value *VisitUnaryPreDec(const UnaryOperator *E) {
302 LValue LV = EmitLValue(E->getSubExpr());
303 return EmitScalarPrePostIncDec(E, LV, false, true);
305 Value *VisitUnaryPreInc(const UnaryOperator *E) {
306 LValue LV = EmitLValue(E->getSubExpr());
307 return EmitScalarPrePostIncDec(E, LV, true, true);
310 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
312 llvm::Value *NextVal,
315 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
316 bool isInc, bool isPre);
319 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
320 if (isa<MemberPointerType>(E->getType())) // never sugared
321 return CGF.CGM.getMemberPointerConstant(E);
323 return EmitLValue(E->getSubExpr()).getAddress();
325 Value *VisitUnaryDeref(const UnaryOperator *E) {
326 if (E->getType()->isVoidType())
327 return Visit(E->getSubExpr()); // the actual value should be unused
328 return EmitLoadOfLValue(E);
330 Value *VisitUnaryPlus(const UnaryOperator *E) {
331 // This differs from gcc, though, most likely due to a bug in gcc.
332 TestAndClearIgnoreResultAssign();
333 return Visit(E->getSubExpr());
335 Value *VisitUnaryMinus (const UnaryOperator *E);
336 Value *VisitUnaryNot (const UnaryOperator *E);
337 Value *VisitUnaryLNot (const UnaryOperator *E);
338 Value *VisitUnaryReal (const UnaryOperator *E);
339 Value *VisitUnaryImag (const UnaryOperator *E);
340 Value *VisitUnaryExtension(const UnaryOperator *E) {
341 return Visit(E->getSubExpr());
345 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
346 return EmitLoadOfLValue(E);
349 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
350 return Visit(DAE->getExpr());
352 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
353 return CGF.LoadCXXThis();
356 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
357 return CGF.EmitExprWithCleanups(E).getScalarVal();
359 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
360 return CGF.EmitCXXNewExpr(E);
362 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
363 CGF.EmitCXXDeleteExpr(E);
366 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
367 return Builder.getInt1(E->getValue());
370 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
371 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
374 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
375 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
378 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
379 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
382 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
383 // C++ [expr.pseudo]p1:
384 // The result shall only be used as the operand for the function call
385 // operator (), and the result of such a call has type void. The only
386 // effect is the evaluation of the postfix-expression before the dot or
388 CGF.EmitScalarExpr(E->getBase());
392 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
393 return EmitNullValue(E->getType());
396 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
397 CGF.EmitCXXThrowExpr(E);
401 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
402 return Builder.getInt1(E->getValue());
406 Value *EmitMul(const BinOpInfo &Ops) {
407 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
408 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
409 case LangOptions::SOB_Undefined:
410 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
411 case LangOptions::SOB_Defined:
412 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
413 case LangOptions::SOB_Trapping:
414 return EmitOverflowCheckedBinOp(Ops);
418 if (Ops.LHS->getType()->isFPOrFPVectorTy())
419 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
420 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
422 bool isTrapvOverflowBehavior() {
423 return CGF.getContext().getLangOptions().getSignedOverflowBehavior()
424 == LangOptions::SOB_Trapping;
426 /// Create a binary op that checks for overflow.
427 /// Currently only supports +, - and *.
428 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
429 // Emit the overflow BB when -ftrapv option is activated.
430 void EmitOverflowBB(llvm::BasicBlock *overflowBB) {
431 Builder.SetInsertPoint(overflowBB);
432 llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
433 Builder.CreateCall(Trap);
434 Builder.CreateUnreachable();
436 // Check for undefined division and modulus behaviors.
437 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
438 llvm::Value *Zero,bool isDiv);
439 Value *EmitDiv(const BinOpInfo &Ops);
440 Value *EmitRem(const BinOpInfo &Ops);
441 Value *EmitAdd(const BinOpInfo &Ops);
442 Value *EmitSub(const BinOpInfo &Ops);
443 Value *EmitShl(const BinOpInfo &Ops);
444 Value *EmitShr(const BinOpInfo &Ops);
445 Value *EmitAnd(const BinOpInfo &Ops) {
446 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
448 Value *EmitXor(const BinOpInfo &Ops) {
449 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
451 Value *EmitOr (const BinOpInfo &Ops) {
452 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
455 BinOpInfo EmitBinOps(const BinaryOperator *E);
456 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
457 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
460 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
461 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
463 // Binary operators and binary compound assignment operators.
464 #define HANDLEBINOP(OP) \
465 Value *VisitBin ## OP(const BinaryOperator *E) { \
466 return Emit ## OP(EmitBinOps(E)); \
468 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
469 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
484 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
485 unsigned SICmpOpc, unsigned FCmpOpc);
486 #define VISITCOMP(CODE, UI, SI, FP) \
487 Value *VisitBin##CODE(const BinaryOperator *E) { \
488 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
489 llvm::FCmpInst::FP); }
490 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
491 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
492 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
493 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
494 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
495 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
498 Value *VisitBinAssign (const BinaryOperator *E);
500 Value *VisitBinLAnd (const BinaryOperator *E);
501 Value *VisitBinLOr (const BinaryOperator *E);
502 Value *VisitBinComma (const BinaryOperator *E);
504 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
505 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
508 Value *VisitBlockExpr(const BlockExpr *BE);
509 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
510 Value *VisitChooseExpr(ChooseExpr *CE);
511 Value *VisitVAArgExpr(VAArgExpr *VE);
512 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
513 return CGF.EmitObjCStringLiteral(E);
515 Value *VisitAsTypeExpr(AsTypeExpr *CE);
516 Value *VisitAtomicExpr(AtomicExpr *AE);
518 } // end anonymous namespace.
520 //===----------------------------------------------------------------------===//
522 //===----------------------------------------------------------------------===//
524 /// EmitConversionToBool - Convert the specified expression value to a
525 /// boolean (i1) truth value. This is equivalent to "Val != 0".
526 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
527 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
529 if (SrcType->isRealFloatingType())
530 return EmitFloatToBoolConversion(Src);
532 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
533 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
535 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
536 "Unknown scalar type to convert");
538 if (isa<llvm::IntegerType>(Src->getType()))
539 return EmitIntToBoolConversion(Src);
541 assert(isa<llvm::PointerType>(Src->getType()));
542 return EmitPointerToBoolConversion(Src);
545 /// EmitScalarConversion - Emit a conversion from the specified type to the
546 /// specified destination type, both of which are LLVM scalar types.
547 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
549 SrcType = CGF.getContext().getCanonicalType(SrcType);
550 DstType = CGF.getContext().getCanonicalType(DstType);
551 if (SrcType == DstType) return Src;
553 if (DstType->isVoidType()) return 0;
555 llvm::Type *SrcTy = Src->getType();
557 // Floating casts might be a bit special: if we're doing casts to / from half
558 // FP, we should go via special intrinsics.
559 if (SrcType->isHalfType()) {
560 Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src);
561 SrcType = CGF.getContext().FloatTy;
562 SrcTy = llvm::Type::getFloatTy(VMContext);
565 // Handle conversions to bool first, they are special: comparisons against 0.
566 if (DstType->isBooleanType())
567 return EmitConversionToBool(Src, SrcType);
569 llvm::Type *DstTy = ConvertType(DstType);
571 // Ignore conversions like int -> uint.
575 // Handle pointer conversions next: pointers can only be converted to/from
576 // other pointers and integers. Check for pointer types in terms of LLVM, as
577 // some native types (like Obj-C id) may map to a pointer type.
578 if (isa<llvm::PointerType>(DstTy)) {
579 // The source value may be an integer, or a pointer.
580 if (isa<llvm::PointerType>(SrcTy))
581 return Builder.CreateBitCast(Src, DstTy, "conv");
583 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
584 // First, convert to the correct width so that we control the kind of
586 llvm::Type *MiddleTy = CGF.IntPtrTy;
587 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
588 llvm::Value* IntResult =
589 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
590 // Then, cast to pointer.
591 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
594 if (isa<llvm::PointerType>(SrcTy)) {
595 // Must be an ptr to int cast.
596 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
597 return Builder.CreatePtrToInt(Src, DstTy, "conv");
600 // A scalar can be splatted to an extended vector of the same element type
601 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
602 // Cast the scalar to element type
603 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
604 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
606 // Insert the element in element zero of an undef vector
607 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
608 llvm::Value *Idx = Builder.getInt32(0);
609 UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
611 // Splat the element across to all elements
612 SmallVector<llvm::Constant*, 16> Args;
613 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
614 for (unsigned i = 0; i != NumElements; ++i)
615 Args.push_back(Builder.getInt32(0));
617 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
618 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
622 // Allow bitcast from vector to integer/fp of the same size.
623 if (isa<llvm::VectorType>(SrcTy) ||
624 isa<llvm::VectorType>(DstTy))
625 return Builder.CreateBitCast(Src, DstTy, "conv");
627 // Finally, we have the arithmetic types: real int/float.
629 llvm::Type *ResTy = DstTy;
631 // Cast to half via float
632 if (DstType->isHalfType())
633 DstTy = llvm::Type::getFloatTy(VMContext);
635 if (isa<llvm::IntegerType>(SrcTy)) {
636 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
637 if (isa<llvm::IntegerType>(DstTy))
638 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
639 else if (InputSigned)
640 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
642 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
643 } else if (isa<llvm::IntegerType>(DstTy)) {
644 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
645 if (DstType->isSignedIntegerOrEnumerationType())
646 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
648 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
650 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
651 "Unknown real conversion");
652 if (DstTy->getTypeID() < SrcTy->getTypeID())
653 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
655 Res = Builder.CreateFPExt(Src, DstTy, "conv");
658 if (DstTy != ResTy) {
659 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
660 Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res);
666 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
667 /// type to the specified destination type, where the destination type is an
668 /// LLVM scalar type.
669 Value *ScalarExprEmitter::
670 EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
671 QualType SrcTy, QualType DstTy) {
672 // Get the source element type.
673 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
675 // Handle conversions to bool first, they are special: comparisons against 0.
676 if (DstTy->isBooleanType()) {
677 // Complex != 0 -> (Real != 0) | (Imag != 0)
678 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
679 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
680 return Builder.CreateOr(Src.first, Src.second, "tobool");
683 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
684 // the imaginary part of the complex value is discarded and the value of the
685 // real part is converted according to the conversion rules for the
686 // corresponding real type.
687 return EmitScalarConversion(Src.first, SrcTy, DstTy);
690 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
691 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
692 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
694 return llvm::Constant::getNullValue(ConvertType(Ty));
697 //===----------------------------------------------------------------------===//
699 //===----------------------------------------------------------------------===//
701 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
702 CGF.ErrorUnsupported(E, "scalar expression");
703 if (E->getType()->isVoidType())
705 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
708 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
710 if (E->getNumSubExprs() == 2 ||
711 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
712 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
713 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
716 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
717 unsigned LHSElts = LTy->getNumElements();
719 if (E->getNumSubExprs() == 3) {
720 Mask = CGF.EmitScalarExpr(E->getExpr(2));
722 // Shuffle LHS & RHS into one input vector.
723 SmallVector<llvm::Constant*, 32> concat;
724 for (unsigned i = 0; i != LHSElts; ++i) {
725 concat.push_back(Builder.getInt32(2*i));
726 concat.push_back(Builder.getInt32(2*i+1));
729 Value* CV = llvm::ConstantVector::get(concat);
730 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
736 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
737 llvm::Constant* EltMask;
739 // Treat vec3 like vec4.
740 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
741 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
742 (1 << llvm::Log2_32(LHSElts+2))-1);
743 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
744 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
745 (1 << llvm::Log2_32(LHSElts+1))-1);
747 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
748 (1 << llvm::Log2_32(LHSElts))-1);
750 // Mask off the high bits of each shuffle index.
751 SmallVector<llvm::Constant *, 32> MaskV;
752 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i)
753 MaskV.push_back(EltMask);
755 Value* MaskBits = llvm::ConstantVector::get(MaskV);
756 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
759 // mask = mask & maskbits
761 // n = extract mask i
763 // newv = insert newv, x, i
764 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
765 MTy->getNumElements());
766 Value* NewV = llvm::UndefValue::get(RTy);
767 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
768 Value *Indx = Builder.getInt32(i);
769 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx");
770 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
772 // Handle vec3 special since the index will be off by one for the RHS.
773 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
774 Value *cmpIndx, *newIndx;
775 cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
777 newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
778 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
780 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
781 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins");
786 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
787 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
789 // Handle vec3 special since the index will be off by one for the RHS.
790 llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
791 SmallVector<llvm::Constant*, 32> indices;
792 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
793 unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
794 if (VTy->getNumElements() == 3 && Idx > 3)
796 indices.push_back(Builder.getInt32(Idx));
799 Value *SV = llvm::ConstantVector::get(indices);
800 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
802 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
803 Expr::EvalResult Result;
804 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
806 CGF.EmitScalarExpr(E->getBase());
808 EmitLValue(E->getBase());
809 return Builder.getInt(Result.Val.getInt());
812 // Emit debug info for aggregate now, if it was delayed to reduce
814 CGDebugInfo *DI = CGF.getDebugInfo();
815 if (DI && CGF.CGM.getCodeGenOpts().LimitDebugInfo) {
816 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
817 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
818 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
819 DI->getOrCreateRecordType(PTy->getPointeeType(),
820 M->getParent()->getLocation());
822 return EmitLoadOfLValue(E);
825 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
826 TestAndClearIgnoreResultAssign();
828 // Emit subscript expressions in rvalue context's. For most cases, this just
829 // loads the lvalue formed by the subscript expr. However, we have to be
830 // careful, because the base of a vector subscript is occasionally an rvalue,
831 // so we can't get it as an lvalue.
832 if (!E->getBase()->getType()->isVectorType())
833 return EmitLoadOfLValue(E);
835 // Handle the vector case. The base must be a vector, the index must be an
837 Value *Base = Visit(E->getBase());
838 Value *Idx = Visit(E->getIdx());
839 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType();
840 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
841 return Builder.CreateExtractElement(Base, Idx, "vecext");
844 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
845 unsigned Off, llvm::Type *I32Ty) {
846 int MV = SVI->getMaskValue(Idx);
848 return llvm::UndefValue::get(I32Ty);
849 return llvm::ConstantInt::get(I32Ty, Off+MV);
852 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
853 bool Ignore = TestAndClearIgnoreResultAssign();
855 assert (Ignore == false && "init list ignored");
856 unsigned NumInitElements = E->getNumInits();
858 if (E->hadArrayRangeDesignator())
859 CGF.ErrorUnsupported(E, "GNU array range designator extension");
861 llvm::VectorType *VType =
862 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
865 if (NumInitElements == 0) {
866 // C++11 value-initialization for the scalar.
867 return EmitNullValue(E->getType());
869 // We have a scalar in braces. Just use the first element.
870 return Visit(E->getInit(0));
873 unsigned ResElts = VType->getNumElements();
875 // Loop over initializers collecting the Value for each, and remembering
876 // whether the source was swizzle (ExtVectorElementExpr). This will allow
877 // us to fold the shuffle for the swizzle into the shuffle for the vector
878 // initializer, since LLVM optimizers generally do not want to touch
881 bool VIsUndefShuffle = false;
882 llvm::Value *V = llvm::UndefValue::get(VType);
883 for (unsigned i = 0; i != NumInitElements; ++i) {
884 Expr *IE = E->getInit(i);
885 Value *Init = Visit(IE);
886 SmallVector<llvm::Constant*, 16> Args;
888 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
890 // Handle scalar elements. If the scalar initializer is actually one
891 // element of a different vector of the same width, use shuffle instead of
894 if (isa<ExtVectorElementExpr>(IE)) {
895 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
897 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
898 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
899 Value *LHS = 0, *RHS = 0;
901 // insert into undef -> shuffle (src, undef)
903 for (unsigned j = 1; j != ResElts; ++j)
904 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
906 LHS = EI->getVectorOperand();
908 VIsUndefShuffle = true;
909 } else if (VIsUndefShuffle) {
910 // insert into undefshuffle && size match -> shuffle (v, src)
911 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
912 for (unsigned j = 0; j != CurIdx; ++j)
913 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
914 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
915 for (unsigned j = CurIdx + 1; j != ResElts; ++j)
916 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
918 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
919 RHS = EI->getVectorOperand();
920 VIsUndefShuffle = false;
923 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
924 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
930 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
932 VIsUndefShuffle = false;
937 unsigned InitElts = VVT->getNumElements();
939 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
940 // input is the same width as the vector being constructed, generate an
941 // optimized shuffle of the swizzle input into the result.
942 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
943 if (isa<ExtVectorElementExpr>(IE)) {
944 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
945 Value *SVOp = SVI->getOperand(0);
946 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
948 if (OpTy->getNumElements() == ResElts) {
949 for (unsigned j = 0; j != CurIdx; ++j) {
950 // If the current vector initializer is a shuffle with undef, merge
951 // this shuffle directly into it.
952 if (VIsUndefShuffle) {
953 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
956 Args.push_back(Builder.getInt32(j));
959 for (unsigned j = 0, je = InitElts; j != je; ++j)
960 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
961 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
962 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
965 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
971 // Extend init to result vector length, and then shuffle its contribution
972 // to the vector initializer into V.
974 for (unsigned j = 0; j != InitElts; ++j)
975 Args.push_back(Builder.getInt32(j));
976 for (unsigned j = InitElts; j != ResElts; ++j)
977 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
978 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
979 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
983 for (unsigned j = 0; j != CurIdx; ++j)
984 Args.push_back(Builder.getInt32(j));
985 for (unsigned j = 0; j != InitElts; ++j)
986 Args.push_back(Builder.getInt32(j+Offset));
987 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
988 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
991 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
992 // merging subsequent shuffles into this one.
995 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
996 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
997 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1001 // FIXME: evaluate codegen vs. shuffling against constant null vector.
1002 // Emit remaining default initializers.
1003 llvm::Type *EltTy = VType->getElementType();
1005 // Emit remaining default initializers
1006 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
1007 Value *Idx = Builder.getInt32(CurIdx);
1008 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1009 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1014 static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
1015 const Expr *E = CE->getSubExpr();
1017 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
1020 if (isa<CXXThisExpr>(E)) {
1021 // We always assume that 'this' is never null.
1025 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
1026 // And that glvalue casts are never null.
1027 if (ICE->getValueKind() != VK_RValue)
1034 // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1035 // have to handle a more broad range of conversions than explicit casts, as they
1036 // handle things like function to ptr-to-function decay etc.
1037 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
1038 Expr *E = CE->getSubExpr();
1039 QualType DestTy = CE->getType();
1040 CastKind Kind = CE->getCastKind();
1042 if (!DestTy->isVoidType())
1043 TestAndClearIgnoreResultAssign();
1045 // Since almost all cast kinds apply to scalars, this switch doesn't have
1046 // a default case, so the compiler will warn on a missing case. The cases
1047 // are in the same order as in the CastKind enum.
1049 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1051 case CK_LValueBitCast:
1052 case CK_ObjCObjectLValueCast: {
1053 Value *V = EmitLValue(E).getAddress();
1054 V = Builder.CreateBitCast(V,
1055 ConvertType(CGF.getContext().getPointerType(DestTy)));
1056 return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy));
1059 case CK_CPointerToObjCPointerCast:
1060 case CK_BlockPointerToObjCPointerCast:
1061 case CK_AnyPointerToBlockPointerCast:
1063 Value *Src = Visit(const_cast<Expr*>(E));
1064 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1067 case CK_UserDefinedConversion:
1068 return Visit(const_cast<Expr*>(E));
1070 case CK_BaseToDerived: {
1071 const CXXRecordDecl *DerivedClassDecl =
1072 DestTy->getCXXRecordDeclForPointerType();
1074 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
1075 CE->path_begin(), CE->path_end(),
1076 ShouldNullCheckClassCastValue(CE));
1078 case CK_UncheckedDerivedToBase:
1079 case CK_DerivedToBase: {
1080 const RecordType *DerivedClassTy =
1081 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
1082 CXXRecordDecl *DerivedClassDecl =
1083 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1085 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
1086 CE->path_begin(), CE->path_end(),
1087 ShouldNullCheckClassCastValue(CE));
1090 Value *V = Visit(const_cast<Expr*>(E));
1091 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1092 return CGF.EmitDynamicCast(V, DCE);
1095 case CK_ArrayToPointerDecay: {
1096 assert(E->getType()->isArrayType() &&
1097 "Array to pointer decay must have array source type!");
1099 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1101 // Note that VLA pointers are always decayed, so we don't need to do
1103 if (!E->getType()->isVariableArrayType()) {
1104 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1105 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1106 ->getElementType()) &&
1107 "Expected pointer to array");
1108 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1111 // Make sure the array decay ends up being the right type. This matters if
1112 // the array type was of an incomplete type.
1113 return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType()));
1115 case CK_FunctionToPointerDecay:
1116 return EmitLValue(E).getAddress();
1118 case CK_NullToPointer:
1119 if (MustVisitNullValue(E))
1122 return llvm::ConstantPointerNull::get(
1123 cast<llvm::PointerType>(ConvertType(DestTy)));
1125 case CK_NullToMemberPointer: {
1126 if (MustVisitNullValue(E))
1129 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1130 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1133 case CK_BaseToDerivedMemberPointer:
1134 case CK_DerivedToBaseMemberPointer: {
1135 Value *Src = Visit(E);
1137 // Note that the AST doesn't distinguish between checked and
1138 // unchecked member pointer conversions, so we always have to
1139 // implement checked conversions here. This is inefficient when
1140 // actual control flow may be required in order to perform the
1141 // check, which it is for data member pointers (but not member
1142 // function pointers on Itanium and ARM).
1143 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
1146 case CK_ARCProduceObject:
1147 return CGF.EmitARCRetainScalarExpr(E);
1148 case CK_ARCConsumeObject:
1149 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
1150 case CK_ARCReclaimReturnedObject: {
1151 llvm::Value *value = Visit(E);
1152 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1153 return CGF.EmitObjCConsumeObject(E->getType(), value);
1155 case CK_ARCExtendBlockObject:
1156 return CGF.EmitARCExtendBlockObject(E);
1158 case CK_FloatingRealToComplex:
1159 case CK_FloatingComplexCast:
1160 case CK_IntegralRealToComplex:
1161 case CK_IntegralComplexCast:
1162 case CK_IntegralComplexToFloatingComplex:
1163 case CK_FloatingComplexToIntegralComplex:
1164 case CK_ConstructorConversion:
1166 llvm_unreachable("scalar cast to non-scalar value");
1169 case CK_GetObjCProperty: {
1170 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
1171 assert(E->isGLValue() && E->getObjectKind() == OK_ObjCProperty &&
1172 "CK_GetObjCProperty for non-lvalue or non-ObjCProperty");
1173 RValue RV = CGF.EmitLoadOfLValue(CGF.EmitLValue(E));
1174 return RV.getScalarVal();
1177 case CK_LValueToRValue:
1178 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
1179 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
1180 return Visit(const_cast<Expr*>(E));
1182 case CK_IntegralToPointer: {
1183 Value *Src = Visit(const_cast<Expr*>(E));
1185 // First, convert to the correct width so that we control the kind of
1187 llvm::Type *MiddleTy = CGF.IntPtrTy;
1188 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
1189 llvm::Value* IntResult =
1190 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1192 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
1194 case CK_PointerToIntegral:
1195 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1196 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
1199 CGF.EmitIgnoredExpr(E);
1202 case CK_VectorSplat: {
1203 llvm::Type *DstTy = ConvertType(DestTy);
1204 Value *Elt = Visit(const_cast<Expr*>(E));
1206 // Insert the element in element zero of an undef vector
1207 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
1208 llvm::Value *Idx = Builder.getInt32(0);
1209 UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
1211 // Splat the element across to all elements
1212 SmallVector<llvm::Constant*, 16> Args;
1213 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
1214 llvm::Constant *Zero = Builder.getInt32(0);
1215 for (unsigned i = 0; i < NumElements; i++)
1216 Args.push_back(Zero);
1218 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1219 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1223 case CK_IntegralCast:
1224 case CK_IntegralToFloating:
1225 case CK_FloatingToIntegral:
1226 case CK_FloatingCast:
1227 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
1228 case CK_IntegralToBoolean:
1229 return EmitIntToBoolConversion(Visit(E));
1230 case CK_PointerToBoolean:
1231 return EmitPointerToBoolConversion(Visit(E));
1232 case CK_FloatingToBoolean:
1233 return EmitFloatToBoolConversion(Visit(E));
1234 case CK_MemberPointerToBoolean: {
1235 llvm::Value *MemPtr = Visit(E);
1236 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1237 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
1240 case CK_FloatingComplexToReal:
1241 case CK_IntegralComplexToReal:
1242 return CGF.EmitComplexExpr(E, false, true).first;
1244 case CK_FloatingComplexToBoolean:
1245 case CK_IntegralComplexToBoolean: {
1246 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
1248 // TODO: kill this function off, inline appropriate case here
1249 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1254 llvm_unreachable("unknown scalar cast");
1258 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
1259 CodeGenFunction::StmtExprEvaluation eval(CGF);
1260 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1264 Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
1265 LValue LV = CGF.EmitBlockDeclRefLValue(E);
1266 return CGF.EmitLoadOfLValue(LV).getScalarVal();
1269 //===----------------------------------------------------------------------===//
1271 //===----------------------------------------------------------------------===//
1273 llvm::Value *ScalarExprEmitter::
1274 EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1276 llvm::Value *NextVal, bool IsInc) {
1277 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1278 case LangOptions::SOB_Undefined:
1279 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1281 case LangOptions::SOB_Defined:
1282 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1284 case LangOptions::SOB_Trapping:
1287 BinOp.RHS = NextVal;
1288 BinOp.Ty = E->getType();
1289 BinOp.Opcode = BO_Add;
1291 return EmitOverflowCheckedBinOp(BinOp);
1293 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
1297 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1298 bool isInc, bool isPre) {
1300 QualType type = E->getSubExpr()->getType();
1301 llvm::Value *value = EmitLoadOfLValue(LV);
1302 llvm::Value *input = value;
1304 int amount = (isInc ? 1 : -1);
1306 // Special case of integer increment that we have to check first: bool++.
1307 // Due to promotion rules, we get:
1308 // bool++ -> bool = bool + 1
1309 // -> bool = (int)bool + 1
1310 // -> bool = ((int)bool + 1 != 0)
1311 // An interesting aspect of this is that increment is always true.
1312 // Decrement does not have this property.
1313 if (isInc && type->isBooleanType()) {
1314 value = Builder.getTrue();
1316 // Most common case by far: integer increment.
1317 } else if (type->isIntegerType()) {
1319 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1321 // Note that signed integer inc/dec with width less than int can't
1322 // overflow because of promotion rules; we're just eliding a few steps here.
1323 if (type->isSignedIntegerOrEnumerationType() &&
1324 value->getType()->getPrimitiveSizeInBits() >=
1325 CGF.IntTy->getBitWidth())
1326 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
1328 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1330 // Next most common: pointer increment.
1331 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1332 QualType type = ptr->getPointeeType();
1334 // VLA types don't have constant size.
1335 if (const VariableArrayType *vla
1336 = CGF.getContext().getAsVariableArrayType(type)) {
1337 llvm::Value *numElts = CGF.getVLASize(vla).first;
1338 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
1339 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1340 value = Builder.CreateGEP(value, numElts, "vla.inc");
1342 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
1344 // Arithmetic on function pointers (!) is just +-1.
1345 } else if (type->isFunctionType()) {
1346 llvm::Value *amt = Builder.getInt32(amount);
1348 value = CGF.EmitCastToVoidPtr(value);
1349 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1350 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1352 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
1353 value = Builder.CreateBitCast(value, input->getType());
1355 // For everything else, we can just do a simple increment.
1357 llvm::Value *amt = Builder.getInt32(amount);
1358 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1359 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1361 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
1364 // Vector increment/decrement.
1365 } else if (type->isVectorType()) {
1366 if (type->hasIntegerRepresentation()) {
1367 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1369 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1371 value = Builder.CreateFAdd(
1373 llvm::ConstantFP::get(value->getType(), amount),
1374 isInc ? "inc" : "dec");
1378 } else if (type->isRealFloatingType()) {
1379 // Add the inc/dec to the real part.
1382 if (type->isHalfType()) {
1383 // Another special case: half FP increment should be done via float
1385 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16),
1389 if (value->getType()->isFloatTy())
1390 amt = llvm::ConstantFP::get(VMContext,
1391 llvm::APFloat(static_cast<float>(amount)));
1392 else if (value->getType()->isDoubleTy())
1393 amt = llvm::ConstantFP::get(VMContext,
1394 llvm::APFloat(static_cast<double>(amount)));
1396 llvm::APFloat F(static_cast<float>(amount));
1398 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1400 amt = llvm::ConstantFP::get(VMContext, F);
1402 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1404 if (type->isHalfType())
1406 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16),
1409 // Objective-C pointer types.
1411 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1412 value = CGF.EmitCastToVoidPtr(value);
1414 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1415 if (!isInc) size = -size;
1416 llvm::Value *sizeValue =
1417 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1419 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1420 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1422 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
1423 value = Builder.CreateBitCast(value, input->getType());
1426 // Store the updated result through the lvalue.
1427 if (LV.isBitField())
1428 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
1430 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
1432 // If this is a postinc, return the value read from memory, otherwise use the
1434 return isPre ? value : input;
1439 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
1440 TestAndClearIgnoreResultAssign();
1441 // Emit unary minus with EmitSub so we handle overflow cases etc.
1443 BinOp.RHS = Visit(E->getSubExpr());
1445 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1446 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1448 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
1449 BinOp.Ty = E->getType();
1450 BinOp.Opcode = BO_Sub;
1452 return EmitSub(BinOp);
1455 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
1456 TestAndClearIgnoreResultAssign();
1457 Value *Op = Visit(E->getSubExpr());
1458 return Builder.CreateNot(Op, "neg");
1461 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1462 // Compare operand to zero.
1463 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
1466 // TODO: Could dynamically modify easy computations here. For example, if
1467 // the operand is an icmp ne, turn into icmp eq.
1468 BoolVal = Builder.CreateNot(BoolVal, "lnot");
1470 // ZExt result to the expr type.
1471 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
1474 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1475 // Try folding the offsetof to a constant.
1476 Expr::EvalResult EvalResult;
1477 if (E->Evaluate(EvalResult, CGF.getContext()))
1478 return Builder.getInt(EvalResult.Val.getInt());
1480 // Loop over the components of the offsetof to compute the value.
1481 unsigned n = E->getNumComponents();
1482 llvm::Type* ResultType = ConvertType(E->getType());
1483 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1484 QualType CurrentType = E->getTypeSourceInfo()->getType();
1485 for (unsigned i = 0; i != n; ++i) {
1486 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
1487 llvm::Value *Offset = 0;
1488 switch (ON.getKind()) {
1489 case OffsetOfExpr::OffsetOfNode::Array: {
1490 // Compute the index
1491 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1492 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
1493 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
1494 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1496 // Save the element type
1498 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1500 // Compute the element size
1501 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1502 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1504 // Multiply out to compute the result
1505 Offset = Builder.CreateMul(Idx, ElemSize);
1509 case OffsetOfExpr::OffsetOfNode::Field: {
1510 FieldDecl *MemberDecl = ON.getField();
1511 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1512 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1514 // Compute the index of the field in its parent.
1516 // FIXME: It would be nice if we didn't have to loop here!
1517 for (RecordDecl::field_iterator Field = RD->field_begin(),
1518 FieldEnd = RD->field_end();
1519 Field != FieldEnd; (void)++Field, ++i) {
1520 if (*Field == MemberDecl)
1523 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1525 // Compute the offset to the field
1526 int64_t OffsetInt = RL.getFieldOffset(i) /
1527 CGF.getContext().getCharWidth();
1528 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1530 // Save the element type.
1531 CurrentType = MemberDecl->getType();
1535 case OffsetOfExpr::OffsetOfNode::Identifier:
1536 llvm_unreachable("dependent __builtin_offsetof");
1538 case OffsetOfExpr::OffsetOfNode::Base: {
1539 if (ON.getBase()->isVirtual()) {
1540 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1544 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1545 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1547 // Save the element type.
1548 CurrentType = ON.getBase()->getType();
1550 // Compute the offset to the base.
1551 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1552 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
1553 int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) /
1554 CGF.getContext().getCharWidth();
1555 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1559 Result = Builder.CreateAdd(Result, Offset);
1564 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
1565 /// argument of the sizeof expression as an integer.
1567 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1568 const UnaryExprOrTypeTraitExpr *E) {
1569 QualType TypeToSize = E->getTypeOfArgument();
1570 if (E->getKind() == UETT_SizeOf) {
1571 if (const VariableArrayType *VAT =
1572 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1573 if (E->isArgumentType()) {
1574 // sizeof(type) - make sure to emit the VLA size.
1575 CGF.EmitVariablyModifiedType(TypeToSize);
1577 // C99 6.5.3.4p2: If the argument is an expression of type
1578 // VLA, it is evaluated.
1579 CGF.EmitIgnoredExpr(E->getArgumentExpr());
1583 llvm::Value *numElts;
1584 llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
1586 llvm::Value *size = numElts;
1588 // Scale the number of non-VLA elements by the non-VLA element size.
1589 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1590 if (!eltSize.isOne())
1591 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1597 // If this isn't sizeof(vla), the result must be constant; use the constant
1598 // folding logic so we don't have to duplicate it here.
1599 Expr::EvalResult Result;
1600 E->Evaluate(Result, CGF.getContext());
1601 return Builder.getInt(Result.Val.getInt());
1604 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1605 Expr *Op = E->getSubExpr();
1606 if (Op->getType()->isAnyComplexType()) {
1607 // If it's an l-value, load through the appropriate subobject l-value.
1608 // Note that we have to ask E because Op might be an l-value that
1609 // this won't work for, e.g. an Obj-C property.
1611 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
1613 // Otherwise, calculate and project.
1614 return CGF.EmitComplexExpr(Op, false, true).first;
1620 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1621 Expr *Op = E->getSubExpr();
1622 if (Op->getType()->isAnyComplexType()) {
1623 // If it's an l-value, load through the appropriate subobject l-value.
1624 // Note that we have to ask E because Op might be an l-value that
1625 // this won't work for, e.g. an Obj-C property.
1626 if (Op->isGLValue())
1627 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
1629 // Otherwise, calculate and project.
1630 return CGF.EmitComplexExpr(Op, true, false).second;
1633 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1634 // effects are evaluated, but not the actual value.
1635 CGF.EmitScalarExpr(Op, true);
1636 return llvm::Constant::getNullValue(ConvertType(E->getType()));
1639 //===----------------------------------------------------------------------===//
1641 //===----------------------------------------------------------------------===//
1643 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
1644 TestAndClearIgnoreResultAssign();
1646 Result.LHS = Visit(E->getLHS());
1647 Result.RHS = Visit(E->getRHS());
1648 Result.Ty = E->getType();
1649 Result.Opcode = E->getOpcode();
1654 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1655 const CompoundAssignOperator *E,
1656 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
1658 QualType LHSTy = E->getLHS()->getType();
1661 if (E->getComputationResultType()->isAnyComplexType()) {
1662 // This needs to go through the complex expression emitter, but it's a tad
1663 // complicated to do that... I'm leaving it out for now. (Note that we do
1664 // actually need the imaginary part of the RHS for multiplication and
1666 CGF.ErrorUnsupported(E, "complex compound assignment");
1667 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
1671 // Emit the RHS first. __block variables need to have the rhs evaluated
1672 // first, plus this should improve codegen a little.
1673 OpInfo.RHS = Visit(E->getRHS());
1674 OpInfo.Ty = E->getComputationResultType();
1675 OpInfo.Opcode = E->getOpcode();
1677 // Load/convert the LHS.
1678 LValue LHSLV = EmitCheckedLValue(E->getLHS());
1679 OpInfo.LHS = EmitLoadOfLValue(LHSLV);
1680 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1681 E->getComputationLHSType());
1683 // Expand the binary operator.
1684 Result = (this->*Func)(OpInfo);
1686 // Convert the result back to the LHS type.
1687 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
1689 // Store the result value into the LHS lvalue. Bit-fields are handled
1690 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1691 // 'An assignment expression has the value of the left operand after the
1693 if (LHSLV.isBitField())
1694 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
1696 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
1701 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1702 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1703 bool Ignore = TestAndClearIgnoreResultAssign();
1705 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1707 // If the result is clearly ignored, return now.
1711 // The result of an assignment in C is the assigned r-value.
1712 if (!CGF.getContext().getLangOptions().CPlusPlus)
1715 // Objective-C property assignment never reloads the value following a store.
1716 if (LHS.isPropertyRef())
1719 // If the lvalue is non-volatile, return the computed value of the assignment.
1720 if (!LHS.isVolatileQualified())
1723 // Otherwise, reload the value.
1724 return EmitLoadOfLValue(LHS);
1727 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
1728 const BinOpInfo &Ops,
1729 llvm::Value *Zero, bool isDiv) {
1730 llvm::Function::iterator insertPt = Builder.GetInsertBlock();
1731 llvm::BasicBlock *contBB =
1732 CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn,
1733 llvm::next(insertPt));
1734 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1736 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
1738 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1739 llvm::Value *IntMin =
1740 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
1741 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1743 llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero);
1744 llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin);
1745 llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne);
1746 llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and");
1747 Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"),
1748 overflowBB, contBB);
1750 CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero),
1751 overflowBB, contBB);
1753 EmitOverflowBB(overflowBB);
1754 Builder.SetInsertPoint(contBB);
1757 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
1758 if (isTrapvOverflowBehavior()) {
1759 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1761 if (Ops.Ty->isIntegerType())
1762 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
1763 else if (Ops.Ty->isRealFloatingType()) {
1764 llvm::Function::iterator insertPt = Builder.GetInsertBlock();
1765 llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn,
1766 llvm::next(insertPt));
1767 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow",
1769 CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero),
1770 overflowBB, DivCont);
1771 EmitOverflowBB(overflowBB);
1772 Builder.SetInsertPoint(DivCont);
1775 if (Ops.LHS->getType()->isFPOrFPVectorTy())
1776 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
1777 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
1778 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1780 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1783 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1784 // Rem in C can't be a floating point type: C99 6.5.5p2.
1785 if (isTrapvOverflowBehavior()) {
1786 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1788 if (Ops.Ty->isIntegerType())
1789 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1792 if (Ops.Ty->hasUnsignedIntegerRepresentation())
1793 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1795 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1798 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1802 switch (Ops.Opcode) {
1806 IID = llvm::Intrinsic::sadd_with_overflow;
1811 IID = llvm::Intrinsic::ssub_with_overflow;
1816 IID = llvm::Intrinsic::smul_with_overflow;
1819 llvm_unreachable("Unsupported operation for overflow detection");
1825 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1827 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
1829 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1830 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1831 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1833 // Branch in case of overflow.
1834 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
1835 llvm::Function::iterator insertPt = initialBB;
1836 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
1837 llvm::next(insertPt));
1838 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1840 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1842 // Handle overflow with llvm.trap.
1843 const std::string *handlerName =
1844 &CGF.getContext().getLangOptions().OverflowHandler;
1845 if (handlerName->empty()) {
1846 EmitOverflowBB(overflowBB);
1847 Builder.SetInsertPoint(continueBB);
1851 // If an overflow handler is set, then we want to call it and then use its
1852 // result, if it returns.
1853 Builder.SetInsertPoint(overflowBB);
1855 // Get the overflow handler.
1856 llvm::Type *Int8Ty = llvm::Type::getInt8Ty(VMContext);
1857 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
1858 llvm::FunctionType *handlerTy =
1859 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
1860 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
1862 // Sign extend the args to 64-bit, so that we can use the same handler for
1863 // all types of overflow.
1864 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
1865 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
1867 // Call the handler with the two arguments, the operation, and the size of
1869 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
1870 Builder.getInt8(OpID),
1871 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
1873 // Truncate the result back to the desired size.
1874 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1875 Builder.CreateBr(continueBB);
1877 Builder.SetInsertPoint(continueBB);
1878 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
1879 phi->addIncoming(result, initialBB);
1880 phi->addIncoming(handlerResult, overflowBB);
1885 /// Emit pointer + index arithmetic.
1886 static Value *emitPointerArithmetic(CodeGenFunction &CGF,
1887 const BinOpInfo &op,
1888 bool isSubtraction) {
1889 // Must have binary (not unary) expr here. Unary pointer
1890 // increment/decrement doesn't use this path.
1891 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
1893 Value *pointer = op.LHS;
1894 Expr *pointerOperand = expr->getLHS();
1895 Value *index = op.RHS;
1896 Expr *indexOperand = expr->getRHS();
1898 // In a subtraction, the LHS is always the pointer.
1899 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
1900 std::swap(pointer, index);
1901 std::swap(pointerOperand, indexOperand);
1904 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
1905 if (width != CGF.PointerWidthInBits) {
1906 // Zero-extend or sign-extend the pointer value according to
1907 // whether the index is signed or not.
1908 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
1909 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
1913 // If this is subtraction, negate the index.
1915 index = CGF.Builder.CreateNeg(index, "idx.neg");
1917 const PointerType *pointerType
1918 = pointerOperand->getType()->getAs<PointerType>();
1920 QualType objectType = pointerOperand->getType()
1921 ->castAs<ObjCObjectPointerType>()
1923 llvm::Value *objectSize
1924 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
1926 index = CGF.Builder.CreateMul(index, objectSize);
1928 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1929 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1930 return CGF.Builder.CreateBitCast(result, pointer->getType());
1933 QualType elementType = pointerType->getPointeeType();
1934 if (const VariableArrayType *vla
1935 = CGF.getContext().getAsVariableArrayType(elementType)) {
1936 // The element count here is the total number of non-VLA elements.
1937 llvm::Value *numElements = CGF.getVLASize(vla).first;
1939 // Effectively, the multiply by the VLA size is part of the GEP.
1940 // GEP indexes are signed, and scaling an index isn't permitted to
1941 // signed-overflow, so we use the same semantics for our explicit
1942 // multiply. We suppress this if overflow is not undefined behavior.
1943 if (CGF.getLangOptions().isSignedOverflowDefined()) {
1944 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
1945 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1947 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
1948 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
1953 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1954 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1956 if (elementType->isVoidType() || elementType->isFunctionType()) {
1957 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1958 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1959 return CGF.Builder.CreateBitCast(result, pointer->getType());
1962 if (CGF.getLangOptions().isSignedOverflowDefined())
1963 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1965 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
1968 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
1969 if (op.LHS->getType()->isPointerTy() ||
1970 op.RHS->getType()->isPointerTy())
1971 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
1973 if (op.Ty->isSignedIntegerOrEnumerationType()) {
1974 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1975 case LangOptions::SOB_Undefined:
1976 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
1977 case LangOptions::SOB_Defined:
1978 return Builder.CreateAdd(op.LHS, op.RHS, "add");
1979 case LangOptions::SOB_Trapping:
1980 return EmitOverflowCheckedBinOp(op);
1984 if (op.LHS->getType()->isFPOrFPVectorTy())
1985 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
1987 return Builder.CreateAdd(op.LHS, op.RHS, "add");
1990 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
1991 // The LHS is always a pointer if either side is.
1992 if (!op.LHS->getType()->isPointerTy()) {
1993 if (op.Ty->isSignedIntegerOrEnumerationType()) {
1994 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1995 case LangOptions::SOB_Undefined:
1996 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
1997 case LangOptions::SOB_Defined:
1998 return Builder.CreateSub(op.LHS, op.RHS, "sub");
1999 case LangOptions::SOB_Trapping:
2000 return EmitOverflowCheckedBinOp(op);
2004 if (op.LHS->getType()->isFPOrFPVectorTy())
2005 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
2007 return Builder.CreateSub(op.LHS, op.RHS, "sub");
2010 // If the RHS is not a pointer, then we have normal pointer
2012 if (!op.RHS->getType()->isPointerTy())
2013 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
2015 // Otherwise, this is a pointer subtraction.
2017 // Do the raw subtraction part.
2019 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2021 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2022 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
2024 // Okay, figure out the element size.
2025 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2026 QualType elementType = expr->getLHS()->getType()->getPointeeType();
2028 llvm::Value *divisor = 0;
2030 // For a variable-length array, this is going to be non-constant.
2031 if (const VariableArrayType *vla
2032 = CGF.getContext().getAsVariableArrayType(elementType)) {
2033 llvm::Value *numElements;
2034 llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
2036 divisor = numElements;
2038 // Scale the number of non-VLA elements by the non-VLA element size.
2039 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2040 if (!eltSize.isOne())
2041 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2043 // For everything elese, we can just compute it, safe in the
2044 // assumption that Sema won't let anything through that we can't
2045 // safely compute the size of.
2047 CharUnits elementSize;
2048 // Handle GCC extension for pointer arithmetic on void* and
2049 // function pointer types.
2050 if (elementType->isVoidType() || elementType->isFunctionType())
2051 elementSize = CharUnits::One();
2053 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2055 // Don't even emit the divide for element size of 1.
2056 if (elementSize.isOne())
2059 divisor = CGF.CGM.getSize(elementSize);
2062 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2063 // pointer difference in C is only defined in the case where both operands
2064 // are pointing to elements of an array.
2065 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
2068 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2069 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2070 // RHS to the same size as the LHS.
2071 Value *RHS = Ops.RHS;
2072 if (Ops.LHS->getType() != RHS->getType())
2073 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2075 if (CGF.CatchUndefined
2076 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2077 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2078 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2079 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2080 llvm::ConstantInt::get(RHS->getType(), Width)),
2081 Cont, CGF.getTrapBB());
2082 CGF.EmitBlock(Cont);
2085 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2088 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2089 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2090 // RHS to the same size as the LHS.
2091 Value *RHS = Ops.RHS;
2092 if (Ops.LHS->getType() != RHS->getType())
2093 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2095 if (CGF.CatchUndefined
2096 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2097 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2098 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2099 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2100 llvm::ConstantInt::get(RHS->getType(), Width)),
2101 Cont, CGF.getTrapBB());
2102 CGF.EmitBlock(Cont);
2105 if (Ops.Ty->hasUnsignedIntegerRepresentation())
2106 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2107 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2110 enum IntrinsicType { VCMPEQ, VCMPGT };
2111 // return corresponding comparison intrinsic for given vector type
2112 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2113 BuiltinType::Kind ElemKind) {
2115 default: llvm_unreachable("unexpected element type");
2116 case BuiltinType::Char_U:
2117 case BuiltinType::UChar:
2118 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2119 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
2121 case BuiltinType::Char_S:
2122 case BuiltinType::SChar:
2123 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2124 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
2126 case BuiltinType::UShort:
2127 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2128 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
2130 case BuiltinType::Short:
2131 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2132 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
2134 case BuiltinType::UInt:
2135 case BuiltinType::ULong:
2136 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2137 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
2139 case BuiltinType::Int:
2140 case BuiltinType::Long:
2141 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2142 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
2144 case BuiltinType::Float:
2145 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2146 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
2149 return llvm::Intrinsic::not_intrinsic;
2152 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2153 unsigned SICmpOpc, unsigned FCmpOpc) {
2154 TestAndClearIgnoreResultAssign();
2156 QualType LHSTy = E->getLHS()->getType();
2157 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
2158 assert(E->getOpcode() == BO_EQ ||
2159 E->getOpcode() == BO_NE);
2160 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2161 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
2162 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
2163 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
2164 } else if (!LHSTy->isAnyComplexType()) {
2165 Value *LHS = Visit(E->getLHS());
2166 Value *RHS = Visit(E->getRHS());
2168 // If AltiVec, the comparison results in a numeric type, so we use
2169 // intrinsics comparing vectors and giving 0 or 1 as a result
2170 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
2171 // constants for mapping CR6 register bits to predicate result
2172 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2174 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2176 // in several cases vector arguments order will be reversed
2177 Value *FirstVecArg = LHS,
2178 *SecondVecArg = RHS;
2180 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
2181 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
2182 BuiltinType::Kind ElementKind = BTy->getKind();
2184 switch(E->getOpcode()) {
2185 default: llvm_unreachable("is not a comparison operation");
2188 ID = GetIntrinsic(VCMPEQ, ElementKind);
2192 ID = GetIntrinsic(VCMPEQ, ElementKind);
2196 ID = GetIntrinsic(VCMPGT, ElementKind);
2197 std::swap(FirstVecArg, SecondVecArg);
2201 ID = GetIntrinsic(VCMPGT, ElementKind);
2204 if (ElementKind == BuiltinType::Float) {
2206 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2207 std::swap(FirstVecArg, SecondVecArg);
2211 ID = GetIntrinsic(VCMPGT, ElementKind);
2215 if (ElementKind == BuiltinType::Float) {
2217 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2221 ID = GetIntrinsic(VCMPGT, ElementKind);
2222 std::swap(FirstVecArg, SecondVecArg);
2227 Value *CR6Param = Builder.getInt32(CR6);
2228 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2229 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2230 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2233 if (LHS->getType()->isFPOrFPVectorTy()) {
2234 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
2236 } else if (LHSTy->hasSignedIntegerRepresentation()) {
2237 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
2240 // Unsigned integers and pointers.
2241 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2245 // If this is a vector comparison, sign extend the result to the appropriate
2246 // vector integer type and return it (don't convert to bool).
2247 if (LHSTy->isVectorType())
2248 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2251 // Complex Comparison: can only be an equality comparison.
2252 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2253 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
2255 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
2257 Value *ResultR, *ResultI;
2258 if (CETy->isRealFloatingType()) {
2259 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2260 LHS.first, RHS.first, "cmp.r");
2261 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2262 LHS.second, RHS.second, "cmp.i");
2264 // Complex comparisons can only be equality comparisons. As such, signed
2265 // and unsigned opcodes are the same.
2266 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2267 LHS.first, RHS.first, "cmp.r");
2268 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2269 LHS.second, RHS.second, "cmp.i");
2272 if (E->getOpcode() == BO_EQ) {
2273 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2275 assert(E->getOpcode() == BO_NE &&
2276 "Complex comparison other than == or != ?");
2277 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2281 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2284 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
2285 bool Ignore = TestAndClearIgnoreResultAssign();
2290 switch (E->getLHS()->getType().getObjCLifetime()) {
2291 case Qualifiers::OCL_Strong:
2292 llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2295 case Qualifiers::OCL_Autoreleasing:
2296 llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
2299 case Qualifiers::OCL_Weak:
2300 RHS = Visit(E->getRHS());
2301 LHS = EmitCheckedLValue(E->getLHS());
2302 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2305 // No reason to do any of these differently.
2306 case Qualifiers::OCL_None:
2307 case Qualifiers::OCL_ExplicitNone:
2308 // __block variables need to have the rhs evaluated first, plus
2309 // this should improve codegen just a little.
2310 RHS = Visit(E->getRHS());
2311 LHS = EmitCheckedLValue(E->getLHS());
2313 // Store the value into the LHS. Bit-fields are handled specially
2314 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2315 // 'An assignment expression has the value of the left operand after
2316 // the assignment...'.
2317 if (LHS.isBitField())
2318 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
2320 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
2323 // If the result is clearly ignored, return now.
2327 // The result of an assignment in C is the assigned r-value.
2328 if (!CGF.getContext().getLangOptions().CPlusPlus)
2331 // Objective-C property assignment never reloads the value following a store.
2332 if (LHS.isPropertyRef())
2335 // If the lvalue is non-volatile, return the computed value of the assignment.
2336 if (!LHS.isVolatileQualified())
2339 // Otherwise, reload the value.
2340 return EmitLoadOfLValue(LHS);
2343 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
2344 llvm::Type *ResTy = ConvertType(E->getType());
2346 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2347 // If we have 1 && X, just emit X without inserting the control flow.
2349 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2350 if (LHSCondVal) { // If we have 1 && X, just emit X.
2351 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2352 // ZExt result to int or bool.
2353 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
2356 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
2357 if (!CGF.ContainsLabel(E->getRHS()))
2358 return llvm::Constant::getNullValue(ResTy);
2361 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2362 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
2364 CodeGenFunction::ConditionalEvaluation eval(CGF);
2366 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2367 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2369 // Any edges into the ContBlock are now from an (indeterminate number of)
2370 // edges from this first condition. All of these values will be false. Start
2371 // setting up the PHI node in the Cont Block for this.
2372 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
2374 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2376 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
2379 CGF.EmitBlock(RHSBlock);
2380 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2383 // Reaquire the RHS block, as there may be subblocks inserted.
2384 RHSBlock = Builder.GetInsertBlock();
2386 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2387 // into the phi node for the edge with the value of RHSCond.
2388 if (CGF.getDebugInfo())
2389 // There is no need to emit line number for unconditional branch.
2390 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
2391 CGF.EmitBlock(ContBlock);
2392 PN->addIncoming(RHSCond, RHSBlock);
2394 // ZExt result to int.
2395 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
2398 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
2399 llvm::Type *ResTy = ConvertType(E->getType());
2401 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2402 // If we have 0 || X, just emit X without inserting the control flow.
2404 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2405 if (!LHSCondVal) { // If we have 0 || X, just emit X.
2406 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2407 // ZExt result to int or bool.
2408 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
2411 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
2412 if (!CGF.ContainsLabel(E->getRHS()))
2413 return llvm::ConstantInt::get(ResTy, 1);
2416 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2417 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
2419 CodeGenFunction::ConditionalEvaluation eval(CGF);
2421 // Branch on the LHS first. If it is true, go to the success (cont) block.
2422 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2424 // Any edges into the ContBlock are now from an (indeterminate number of)
2425 // edges from this first condition. All of these values will be true. Start
2426 // setting up the PHI node in the Cont Block for this.
2427 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
2429 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2431 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
2435 // Emit the RHS condition as a bool value.
2436 CGF.EmitBlock(RHSBlock);
2437 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2441 // Reaquire the RHS block, as there may be subblocks inserted.
2442 RHSBlock = Builder.GetInsertBlock();
2444 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2445 // into the phi node for the edge with the value of RHSCond.
2446 CGF.EmitBlock(ContBlock);
2447 PN->addIncoming(RHSCond, RHSBlock);
2449 // ZExt result to int.
2450 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
2453 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
2454 CGF.EmitIgnoredExpr(E->getLHS());
2455 CGF.EnsureInsertPoint();
2456 return Visit(E->getRHS());
2459 //===----------------------------------------------------------------------===//
2461 //===----------------------------------------------------------------------===//
2463 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2464 /// expression is cheap enough and side-effect-free enough to evaluate
2465 /// unconditionally instead of conditionally. This is used to convert control
2466 /// flow into selects in some cases.
2467 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2468 CodeGenFunction &CGF) {
2469 E = E->IgnoreParens();
2471 // Anything that is an integer or floating point constant is fine.
2472 if (E->isConstantInitializer(CGF.getContext(), false))
2475 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2476 // X and Y are local variables.
2477 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2478 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2479 if (VD->hasLocalStorage() && !(CGF.getContext()
2480 .getCanonicalType(VD->getType())
2481 .isVolatileQualified()))
2488 Value *ScalarExprEmitter::
2489 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
2490 TestAndClearIgnoreResultAssign();
2492 // Bind the common expression if necessary.
2493 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
2495 Expr *condExpr = E->getCond();
2496 Expr *lhsExpr = E->getTrueExpr();
2497 Expr *rhsExpr = E->getFalseExpr();
2499 // If the condition constant folds and can be elided, try to avoid emitting
2500 // the condition and the dead arm.
2502 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
2503 Expr *live = lhsExpr, *dead = rhsExpr;
2504 if (!CondExprBool) std::swap(live, dead);
2506 // If the dead side doesn't have labels we need, and if the Live side isn't
2507 // the gnu missing ?: extension (which we could handle, but don't bother
2508 // to), just emit the Live part.
2509 if (!CGF.ContainsLabel(dead))
2513 // OpenCL: If the condition is a vector, we can treat this condition like
2514 // the select function.
2515 if (CGF.getContext().getLangOptions().OpenCL
2516 && condExpr->getType()->isVectorType()) {
2517 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
2518 llvm::Value *LHS = Visit(lhsExpr);
2519 llvm::Value *RHS = Visit(rhsExpr);
2521 llvm::Type *condType = ConvertType(condExpr->getType());
2522 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
2524 unsigned numElem = vecTy->getNumElements();
2525 llvm::Type *elemType = vecTy->getElementType();
2527 std::vector<llvm::Constant*> Zvals;
2528 for (unsigned i = 0; i < numElem; ++i)
2529 Zvals.push_back(llvm::ConstantInt::get(elemType, 0));
2531 llvm::Value *zeroVec = llvm::ConstantVector::get(Zvals);
2532 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2533 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2534 llvm::VectorType::get(elemType,
2537 llvm::Value *tmp2 = Builder.CreateNot(tmp);
2539 // Cast float to int to perform ANDs if necessary.
2540 llvm::Value *RHSTmp = RHS;
2541 llvm::Value *LHSTmp = LHS;
2542 bool wasCast = false;
2543 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
2544 if (rhsVTy->getElementType()->isFloatTy()) {
2545 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2546 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2550 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2551 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2552 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2554 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2559 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2560 // select instead of as control flow. We can only do this if it is cheap and
2561 // safe to evaluate the LHS and RHS unconditionally.
2562 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
2563 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
2564 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
2565 llvm::Value *LHS = Visit(lhsExpr);
2566 llvm::Value *RHS = Visit(rhsExpr);
2567 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2570 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2571 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
2572 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
2574 CodeGenFunction::ConditionalEvaluation eval(CGF);
2575 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
2577 CGF.EmitBlock(LHSBlock);
2579 Value *LHS = Visit(lhsExpr);
2582 LHSBlock = Builder.GetInsertBlock();
2583 Builder.CreateBr(ContBlock);
2585 CGF.EmitBlock(RHSBlock);
2587 Value *RHS = Visit(rhsExpr);
2590 RHSBlock = Builder.GetInsertBlock();
2591 CGF.EmitBlock(ContBlock);
2593 // If the LHS or RHS is a throw expression, it will be legitimately null.
2599 // Create a PHI node for the real part.
2600 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
2601 PN->addIncoming(LHS, LHSBlock);
2602 PN->addIncoming(RHS, RHSBlock);
2606 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
2607 return Visit(E->getChosenSubExpr(CGF.getContext()));
2610 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
2611 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
2612 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2614 // If EmitVAArg fails, we fall back to the LLVM instruction.
2616 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2618 // FIXME Volatility.
2619 return Builder.CreateLoad(ArgPtr);
2622 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2623 return CGF.EmitBlockLiteral(block);
2626 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
2627 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
2628 llvm::Type *DstTy = ConvertType(E->getType());
2630 // Going from vec4->vec3 or vec3->vec4 is a special case and requires
2631 // a shuffle vector instead of a bitcast.
2632 llvm::Type *SrcTy = Src->getType();
2633 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
2634 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
2635 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
2636 if ((numElementsDst == 3 && numElementsSrc == 4)
2637 || (numElementsDst == 4 && numElementsSrc == 3)) {
2640 // In the case of going from int4->float3, a bitcast is needed before
2642 llvm::Type *srcElemTy =
2643 cast<llvm::VectorType>(SrcTy)->getElementType();
2644 llvm::Type *dstElemTy =
2645 cast<llvm::VectorType>(DstTy)->getElementType();
2647 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
2648 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
2649 // Create a float type of the same size as the source or destination.
2650 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
2653 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
2656 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
2658 SmallVector<llvm::Constant*, 3> Args;
2659 Args.push_back(Builder.getInt32(0));
2660 Args.push_back(Builder.getInt32(1));
2661 Args.push_back(Builder.getInt32(2));
2663 if (numElementsDst == 4)
2664 Args.push_back(llvm::UndefValue::get(
2665 llvm::Type::getInt32Ty(CGF.getLLVMContext())));
2667 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
2669 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
2673 return Builder.CreateBitCast(Src, DstTy, "astype");
2676 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
2677 return CGF.EmitAtomicExpr(E).getScalarVal();
2680 //===----------------------------------------------------------------------===//
2681 // Entry Point into this File
2682 //===----------------------------------------------------------------------===//
2684 /// EmitScalarExpr - Emit the computation of the specified expression of scalar
2685 /// type, ignoring the result.
2686 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
2687 assert(E && !hasAggregateLLVMType(E->getType()) &&
2688 "Invalid scalar expression to emit");
2690 if (isa<CXXDefaultArgExpr>(E))
2692 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
2693 .Visit(const_cast<Expr*>(E));
2694 if (isa<CXXDefaultArgExpr>(E))
2699 /// EmitScalarConversion - Emit a conversion from the specified type to the
2700 /// specified destination type, both of which are LLVM scalar types.
2701 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2703 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2704 "Invalid scalar expression to emit");
2705 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2708 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2709 /// type to the specified destination type, where the destination type is an
2710 /// LLVM scalar type.
2711 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2714 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
2715 "Invalid complex -> scalar conversion");
2716 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2721 llvm::Value *CodeGenFunction::
2722 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2723 bool isInc, bool isPre) {
2724 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2727 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2729 // object->isa or (*object).isa
2730 // Generate code as for: *(Class*)object
2731 // build Class* type
2732 llvm::Type *ClassPtrTy = ConvertType(E->getType());
2734 Expr *BaseExpr = E->getBase();
2735 if (BaseExpr->isRValue()) {
2736 V = CreateTempAlloca(ClassPtrTy, "resval");
2737 llvm::Value *Src = EmitScalarExpr(BaseExpr);
2738 Builder.CreateStore(Src, V);
2739 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
2740 MakeAddrLValue(V, E->getType()));
2743 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2745 V = EmitLValue(BaseExpr).getAddress();
2748 // build Class* type
2749 ClassPtrTy = ClassPtrTy->getPointerTo();
2750 V = Builder.CreateBitCast(V, ClassPtrTy);
2751 return MakeAddrLValue(V, E->getType());
2755 LValue CodeGenFunction::EmitCompoundAssignmentLValue(
2756 const CompoundAssignOperator *E) {
2757 ScalarExprEmitter Scalar(*this);
2759 switch (E->getOpcode()) {
2760 #define COMPOUND_OP(Op) \
2761 case BO_##Op##Assign: \
2762 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
2798 llvm_unreachable("Not valid compound assignment operators");
2801 llvm_unreachable("Unhandled compound assignment operator");