CGExprScalar.cpp revision 235633
126159Sse//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
226159Sse//
366529Smsmith//                     The LLVM Compiler Infrastructure
466529Smsmith//
526159Sse// This file is distributed under the University of Illinois Open Source
626159Sse// License. See LICENSE.TXT for details.
726159Sse//
826159Sse//===----------------------------------------------------------------------===//
926159Sse//
1026159Sse// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
1126159Sse//
1226159Sse//===----------------------------------------------------------------------===//
1326159Sse
1426159Sse#include "clang/Frontend/CodeGenOptions.h"
1526159Sse#include "CodeGenFunction.h"
1626159Sse#include "CGCXXABI.h"
1726159Sse#include "CGObjCRuntime.h"
1826159Sse#include "CodeGenModule.h"
1926159Sse#include "CGDebugInfo.h"
2026159Sse#include "clang/AST/ASTContext.h"
2126159Sse#include "clang/AST/DeclObjC.h"
2226159Sse#include "clang/AST/RecordLayout.h"
2326159Sse#include "clang/AST/StmtVisitor.h"
2426159Sse#include "clang/Basic/TargetInfo.h"
2526159Sse#include "llvm/Constants.h"
2626159Sse#include "llvm/Function.h"
2726159Sse#include "llvm/GlobalVariable.h"
2850477Speter#include "llvm/Intrinsics.h"
2926159Sse#include "llvm/Module.h"
3026159Sse#include "llvm/Support/CFG.h"
316104Sse#include "llvm/Target/TargetData.h"
3266529Smsmith#include <cstdarg>
336734Sbde
3447307Speterusing namespace clang;
3547307Speterusing namespace CodeGen;
3661994Smsmithusing llvm::Value;
3765304Speter
3867185Simp//===----------------------------------------------------------------------===//
3967185Simp//                         Scalar Expression Emitter
4067185Simp//===----------------------------------------------------------------------===//
41100435Simp
42100435Simpnamespace {
4361994Smsmithstruct BinOpInfo {
4466416Speter  Value *LHS;
4566529Smsmith  Value *RHS;
4659294Smsmith  QualType Ty;  // Computation Type.
4759294Smsmith  BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
4859294Smsmith  const Expr *E;      // Entire expr, for error unsupported.  May not be binop.
4969783Smsmith};
5069783Smsmith
5169783Smsmithstatic bool MustVisitNullValue(const Expr *E) {
5269783Smsmith  // If a null pointer expression's type is the C++0x nullptr_t, then
5365176Sdfr  // it's not necessarily a simple constant and it must be evaluated
5465176Sdfr  // for its potential side effects.
5582441Simp  return E->getType()->isNullPtrType();
5682441Simp}
5726159Sse
5826159Sseclass ScalarExprEmitter
5959294Smsmith  : public StmtVisitor<ScalarExprEmitter, Value*> {
6082035Simp  CodeGenFunction &CGF;
616104Sse  CGBuilderTy &Builder;
6282035Simp  bool IgnoreResultAssign;
6382035Simp  llvm::LLVMContext &VMContext;
64103025Sjhbpublic:
6568218Smsmith
6668218Smsmith  ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
6768218Smsmith    : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
6868218Smsmith      VMContext(cgf.getLLVMContext()) {
6968218Smsmith  }
70103017Sjhb
71103017Sjhb  //===--------------------------------------------------------------------===//
7266529Smsmith  //                               Utilities
7366529Smsmith  //===--------------------------------------------------------------------===//
7459294Smsmith
7566529Smsmith  bool TestAndClearIgnoreResultAssign() {
7666529Smsmith    bool I = IgnoreResultAssign;
7759294Smsmith    IgnoreResultAssign = false;
7859294Smsmith    return I;
79103017Sjhb  }
80103017Sjhb
8167185Simp  llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
8297694Simp  LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
8397694Simp  LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); }
8497694Simp
8597694Simp  Value *EmitLoadOfLValue(LValue LV) {
8697694Simp    return CGF.EmitLoadOfLValue(LV).getScalarVal();
8797694Simp  }
8897694Simp
8997694Simp  /// EmitLoadOfLValue - Given an expression with complex type that represents a
9097694Simp  /// value l-value, this method emits the address of the l-value, then loads
9197694Simp  /// and returns the result.
92100435Simp  Value *EmitLoadOfLValue(const Expr *E) {
93100435Simp    return EmitLoadOfLValue(EmitCheckedLValue(E));
94100435Simp  }
9597694Simp
9697694Simp  /// EmitConversionToBool - Convert the specified expression value to a
9782026Speter  /// boolean (i1) truth value.  This is equivalent to "Val != 0".
9882026Speter  Value *EmitConversionToBool(Value *Src, QualType DstTy);
9982026Speter
100100435Simp  /// EmitScalarConversion - Emit a conversion from the specified type to the
10182026Speter  /// specified destination type, both of which are LLVM scalar types.
10282026Speter  Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
10382026Speter
10482026Speter  /// EmitComplexToScalarConversion - Emit a conversion from the specified
10582026Speter  /// complex type to the specified destination type, where the destination type
106100435Simp  /// is an LLVM scalar type.
107100435Simp  Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
10882026Speter                                       QualType SrcTy, QualType DstTy);
10982026Speter
11082441Simp  /// EmitNullValue - Emit a value that corresponds to null for the given type.
11182441Simp  Value *EmitNullValue(QualType Ty);
11282441Simp
113100435Simp  /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
11482441Simp  Value *EmitFloatToBoolConversion(Value *V) {
115102976Sjhb    // Compare against 0.0 for fp scalars.
116100435Simp    llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
117100435Simp    return Builder.CreateFCmpUNE(V, Zero, "tobool");
118100435Simp  }
119100435Simp
120100435Simp  /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
121100435Simp  Value *EmitPointerToBoolConversion(Value *V) {
122100435Simp    Value *Zero = llvm::ConstantPointerNull::get(
123100435Simp                                      cast<llvm::PointerType>(V->getType()));
124100435Simp    return Builder.CreateICmpNE(V, Zero, "tobool");
125100435Simp  }
126100435Simp
127100435Simp  Value *EmitIntToBoolConversion(Value *V) {
128100435Simp    // Because of the type rules of C, we often end up computing a
12982441Simp    // logical value, then zero extending it to int, then wanting it
13082441Simp    // as a logical value again.  Optimize this common case.
13166529Smsmith    if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
13266529Smsmith      if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
13366529Smsmith        Value *Result = ZI->getOperand(0);
13466529Smsmith        // If there aren't any more uses, zap the instruction to save space.
13566529Smsmith        // Note that there can be more uses, for example if this
13659294Smsmith        // is the result of an assignment.
137100435Simp        if (ZI->use_empty())
138100435Simp          ZI->eraseFromParent();
139100435Simp        return Result;
140100435Simp      }
141100435Simp    }
14265176Sdfr
143100435Simp    return Builder.CreateIsNotNull(V, "tobool");
144100435Simp  }
14566529Smsmith
146100435Simp  //===--------------------------------------------------------------------===//
147100435Simp  //                            Visitor Methods
148100435Simp  //===--------------------------------------------------------------------===//
149100435Simp
150100435Simp  Value *Visit(Expr *E) {
151100435Simp    return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
15267185Simp  }
153100435Simp
154100435Simp  Value *VisitStmt(Stmt *S) {
155100435Simp    S->dump(CGF.getContext().getSourceManager());
156100435Simp    llvm_unreachable("Stmt can't have complex result type!");
157100435Simp  }
158100435Simp  Value *VisitExpr(Expr *S);
159100435Simp
160100435Simp  Value *VisitParenExpr(ParenExpr *PE) {
161100435Simp    return Visit(PE->getSubExpr());
162100435Simp  }
163100435Simp  Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
164100435Simp    return Visit(E->getReplacement());
165100435Simp  }
166100435Simp  Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
167100435Simp    return Visit(GE->getResultExpr());
168100435Simp  }
169100435Simp
170100435Simp  // Leaves.
171100435Simp  Value *VisitIntegerLiteral(const IntegerLiteral *E) {
172100435Simp    return Builder.getInt(E->getValue());
173100435Simp  }
174100435Simp  Value *VisitFloatingLiteral(const FloatingLiteral *E) {
175100435Simp    return llvm::ConstantFP::get(VMContext, E->getValue());
176100435Simp  }
177100435Simp  Value *VisitCharacterLiteral(const CharacterLiteral *E) {
178100435Simp    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
179100435Simp  }
180100435Simp  Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
18167185Simp    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
182100435Simp  }
183100435Simp  Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
18459294Smsmith    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
18559294Smsmith  }
18666529Smsmith  Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
18769783Smsmith    return EmitNullValue(E->getType());
18866529Smsmith  }
18971237Speter  Value *VisitGNUNullExpr(const GNUNullExpr *E) {
19069783Smsmith    return EmitNullValue(E->getType());
19159294Smsmith  }
192100435Simp  Value *VisitOffsetOfExpr(OffsetOfExpr *E);
193100435Simp  Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
194100435Simp  Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
19559294Smsmith    llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
19659294Smsmith    return Builder.CreateBitCast(V, ConvertType(E->getType()));
19769783Smsmith  }
19869783Smsmith
19969783Smsmith  Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
200100435Simp    return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
20169783Smsmith  }
202100435Simp
20369783Smsmith  Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
204100435Simp    return CGF.EmitPseudoObjectRValue(E).getScalarVal();
205100435Simp  }
206100435Simp
207100435Simp  Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
208100435Simp    if (E->isGLValue())
209100435Simp      return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
210100435Simp
211100435Simp    // Otherwise, assume the mapping is the scalar directly.
21269783Smsmith    return CGF.getOpaqueRValueMapping(E).getScalarVal();
213100435Simp  }
214100435Simp
21569783Smsmith  // l-values.
216100435Simp  Value *VisitDeclRefExpr(DeclRefExpr *E) {
217100435Simp    if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
218100435Simp      if (result.isReference())
219100435Simp        return EmitLoadOfLValue(result.getReferenceLValue(CGF, E));
220100435Simp      return result.getValue();
221100435Simp    }
222100435Simp    return EmitLoadOfLValue(E);
223100435Simp  }
224100435Simp
225100435Simp  Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
226100435Simp    return CGF.EmitObjCSelectorExpr(E);
227100435Simp  }
228100435Simp  Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
229100435Simp    return CGF.EmitObjCProtocolExpr(E);
230100435Simp  }
231100435Simp  Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
232100435Simp    return EmitLoadOfLValue(E);
233100435Simp  }
234100435Simp  Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
235100435Simp    if (E->getMethodDecl() &&
236100435Simp        E->getMethodDecl()->getResultType()->isReferenceType())
237100435Simp      return EmitLoadOfLValue(E);
238100435Simp    return CGF.EmitObjCMessageExpr(E).getScalarVal();
239100435Simp  }
24069783Smsmith
241100435Simp  Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
24269783Smsmith    LValue LV = CGF.EmitObjCIsaExpr(E);
24395375Simp    Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
244100435Simp    return V;
245100435Simp  }
246100435Simp
247100435Simp  Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
248100435Simp  Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
249100435Simp  Value *VisitMemberExpr(MemberExpr *E);
250100435Simp  Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
251100435Simp  Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
252100435Simp    return EmitLoadOfLValue(E);
25369783Smsmith  }
254100435Simp
25569783Smsmith  Value *VisitInitListExpr(InitListExpr *E);
25669783Smsmith
25766529Smsmith  Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
25866529Smsmith    return CGF.CGM.EmitNullConstant(E->getType());
25966529Smsmith  }
26066529Smsmith  Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
26166529Smsmith    if (E->getType()->isVariablyModifiedType())
26259294Smsmith      CGF.EmitVariablyModifiedType(E->getType());
263100435Simp    return VisitCastExpr(E);
264100435Simp  }
265100435Simp  Value *VisitCastExpr(CastExpr *E);
26659294Smsmith
26759294Smsmith  Value *VisitCallExpr(const CallExpr *E) {
26866529Smsmith    if (E->getCallReturnType()->isReferenceType())
26967185Simp      return EmitLoadOfLValue(E);
27067185Simp
27167311Smsmith    return CGF.EmitCallExpr(E).getScalarVal();
27268218Smsmith  }
27368218Smsmith
27467185Simp  Value *VisitStmtExpr(const StmtExpr *E);
27567185Simp
276103025Sjhb  // Unary Operators.
27767185Simp  Value *VisitUnaryPostDec(const UnaryOperator *E) {
278100435Simp    LValue LV = EmitLValue(E->getSubExpr());
279100435Simp    return EmitScalarPrePostIncDec(E, LV, false, false);
280100435Simp  }
281100435Simp  Value *VisitUnaryPostInc(const UnaryOperator *E) {
282100435Simp    LValue LV = EmitLValue(E->getSubExpr());
28367185Simp    return EmitScalarPrePostIncDec(E, LV, true, false);
284100435Simp  }
285100435Simp  Value *VisitUnaryPreDec(const UnaryOperator *E) {
286100435Simp    LValue LV = EmitLValue(E->getSubExpr());
287100435Simp    return EmitScalarPrePostIncDec(E, LV, false, true);
288100435Simp  }
289100435Simp  Value *VisitUnaryPreInc(const UnaryOperator *E) {
290100435Simp    LValue LV = EmitLValue(E->getSubExpr());
291100435Simp    return EmitScalarPrePostIncDec(E, LV, true, true);
292100435Simp  }
293100435Simp
29467185Simp  llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
295100435Simp                                               llvm::Value *InVal,
296100435Simp                                               llvm::Value *NextVal,
297100435Simp                                               bool IsInc);
298100435Simp
299100435Simp  llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
300100435Simp                                       bool isInc, bool isPre);
301100435Simp
302103025Sjhb
303103025Sjhb  Value *VisitUnaryAddrOf(const UnaryOperator *E) {
304103025Sjhb    if (isa<MemberPointerType>(E->getType())) // never sugared
305103025Sjhb      return CGF.CGM.getMemberPointerConstant(E);
306103025Sjhb
307103025Sjhb    return EmitLValue(E->getSubExpr()).getAddress();
308103025Sjhb  }
309103025Sjhb  Value *VisitUnaryDeref(const UnaryOperator *E) {
31068218Smsmith    if (E->getType()->isVoidType())
311103025Sjhb      return Visit(E->getSubExpr()); // the actual value should be unused
312103025Sjhb    return EmitLoadOfLValue(E);
313103025Sjhb  }
314103025Sjhb  Value *VisitUnaryPlus(const UnaryOperator *E) {
315103025Sjhb    // This differs from gcc, though, most likely due to a bug in gcc.
316100435Simp    TestAndClearIgnoreResultAssign();
317100435Simp    return Visit(E->getSubExpr());
318100435Simp  }
319100435Simp  Value *VisitUnaryMinus    (const UnaryOperator *E);
320100435Simp  Value *VisitUnaryNot      (const UnaryOperator *E);
321100435Simp  Value *VisitUnaryLNot     (const UnaryOperator *E);
322100435Simp  Value *VisitUnaryReal     (const UnaryOperator *E);
323100435Simp  Value *VisitUnaryImag     (const UnaryOperator *E);
324100435Simp  Value *VisitUnaryExtension(const UnaryOperator *E) {
32582465Simp    return Visit(E->getSubExpr());
326100435Simp  }
327100435Simp
328100435Simp  // C++
329100435Simp  Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
330100435Simp    return EmitLoadOfLValue(E);
331100435Simp  }
332100435Simp
333100435Simp  Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
334100435Simp    return Visit(DAE->getExpr());
335100435Simp  }
336100435Simp  Value *VisitCXXThisExpr(CXXThisExpr *TE) {
337100435Simp    return CGF.LoadCXXThis();
338100435Simp  }
339100435Simp
340100435Simp  Value *VisitExprWithCleanups(ExprWithCleanups *E) {
341100435Simp    CGF.enterFullExpression(E);
342100435Simp    CodeGenFunction::RunCleanupsScope Scope(CGF);
343100435Simp    return Visit(E->getSubExpr());
344100435Simp  }
345100435Simp  Value *VisitCXXNewExpr(const CXXNewExpr *E) {
346100435Simp    return CGF.EmitCXXNewExpr(E);
34782441Simp  }
34868218Smsmith  Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
349100435Simp    CGF.EmitCXXDeleteExpr(E);
350100435Simp    return 0;
351100435Simp  }
35267185Simp  Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
35367185Simp    return Builder.getInt1(E->getValue());
35468218Smsmith  }
355103025Sjhb
356103025Sjhb  Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
357103025Sjhb    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
358103025Sjhb  }
359103025Sjhb
360103025Sjhb  Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
361103025Sjhb    return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
362103025Sjhb  }
363103025Sjhb
364103025Sjhb  Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
365103025Sjhb    return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
366103025Sjhb  }
367103025Sjhb
368103025Sjhb  Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
369103025Sjhb    // C++ [expr.pseudo]p1:
370103025Sjhb    //   The result shall only be used as the operand for the function call
371103025Sjhb    //   operator (), and the result of such a call has type void. The only
372103025Sjhb    //   effect is the evaluation of the postfix-expression before the dot or
37368218Smsmith    //   arrow.
37468218Smsmith    CGF.EmitScalarExpr(E->getBase());
37568218Smsmith    return 0;
37668218Smsmith  }
37768218Smsmith
378100435Simp  Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
379100435Simp    return EmitNullValue(E->getType());
38068218Smsmith  }
381100435Simp
382100435Simp  Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
383100435Simp    CGF.EmitCXXThrowExpr(E);
384100435Simp    return 0;
385100435Simp  }
386100435Simp
387100435Simp  Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
38868218Smsmith    return Builder.getInt1(E->getValue());
38967185Simp  }
39067185Simp
39168218Smsmith  // Binary Operators.
39268218Smsmith  Value *EmitMul(const BinOpInfo &Ops) {
39368218Smsmith    if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
39468218Smsmith      switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
39568218Smsmith      case LangOptions::SOB_Undefined:
39668218Smsmith        return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
397100435Simp      case LangOptions::SOB_Defined:
398100435Simp        return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
399100435Simp      case LangOptions::SOB_Trapping:
40068218Smsmith        return EmitOverflowCheckedBinOp(Ops);
401100435Simp      }
402100435Simp    }
403100435Simp
404100435Simp    if (Ops.LHS->getType()->isFPOrFPVectorTy())
405100435Simp      return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
406100435Simp    return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
407100435Simp  }
40868218Smsmith  bool isTrapvOverflowBehavior() {
409100435Simp    return CGF.getContext().getLangOpts().getSignedOverflowBehavior()
410100435Simp               == LangOptions::SOB_Trapping;
411100435Simp  }
412100435Simp  /// Create a binary op that checks for overflow.
413100435Simp  /// Currently only supports +, - and *.
414100435Simp  Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
415100435Simp  // Emit the overflow BB when -ftrapv option is activated.
416100435Simp  void EmitOverflowBB(llvm::BasicBlock *overflowBB) {
417100435Simp    Builder.SetInsertPoint(overflowBB);
418100435Simp    llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
419100435Simp    Builder.CreateCall(Trap);
420100435Simp    Builder.CreateUnreachable();
421100435Simp  }
42268218Smsmith  // Check for undefined division and modulus behaviors.
423100435Simp  void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
424100435Simp                                                  llvm::Value *Zero,bool isDiv);
425100435Simp  Value *EmitDiv(const BinOpInfo &Ops);
426100435Simp  Value *EmitRem(const BinOpInfo &Ops);
427100435Simp  Value *EmitAdd(const BinOpInfo &Ops);
428100435Simp  Value *EmitSub(const BinOpInfo &Ops);
429100435Simp  Value *EmitShl(const BinOpInfo &Ops);
430100435Simp  Value *EmitShr(const BinOpInfo &Ops);
431100435Simp  Value *EmitAnd(const BinOpInfo &Ops) {
43268218Smsmith    return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
433100435Simp  }
43468218Smsmith  Value *EmitXor(const BinOpInfo &Ops) {
43568218Smsmith    return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
43668218Smsmith  }
43768218Smsmith  Value *EmitOr (const BinOpInfo &Ops) {
43868218Smsmith    return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
43968218Smsmith  }
44068218Smsmith
44168218Smsmith  BinOpInfo EmitBinOps(const BinaryOperator *E);
44268218Smsmith  LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
443100435Simp                            Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
444100435Simp                                  Value *&Result);
445100435Simp
446100435Simp  Value *EmitCompoundAssign(const CompoundAssignOperator *E,
447100435Simp                            Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
448100435Simp
449100435Simp  // Binary operators and binary compound assignment operators.
45068218Smsmith#define HANDLEBINOP(OP) \
451100435Simp  Value *VisitBin ## OP(const BinaryOperator *E) {                         \
452100435Simp    return Emit ## OP(EmitBinOps(E));                                      \
453100435Simp  }                                                                        \
454100435Simp  Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
455100435Simp    return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
456100435Simp  }
45768218Smsmith  HANDLEBINOP(Mul)
458100435Simp  HANDLEBINOP(Div)
459100435Simp  HANDLEBINOP(Rem)
460100435Simp  HANDLEBINOP(Add)
461100435Simp  HANDLEBINOP(Sub)
462100435Simp  HANDLEBINOP(Shl)
463100435Simp  HANDLEBINOP(Shr)
464100435Simp  HANDLEBINOP(And)
465100435Simp  HANDLEBINOP(Xor)
46668218Smsmith  HANDLEBINOP(Or)
467100435Simp#undef HANDLEBINOP
468100435Simp
469100435Simp  // Comparisons.
470100435Simp  Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
471100435Simp                     unsigned SICmpOpc, unsigned FCmpOpc);
472100435Simp#define VISITCOMP(CODE, UI, SI, FP) \
473100435Simp    Value *VisitBin##CODE(const BinaryOperator *E) { \
474100435Simp      return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
475100435Simp                         llvm::FCmpInst::FP); }
476100435Simp  VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
477100435Simp  VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
478100435Simp  VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
479100435Simp  VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
480100435Simp  VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
481100435Simp  VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
482100435Simp#undef VISITCOMP
483100435Simp
48468218Smsmith  Value *VisitBinAssign     (const BinaryOperator *E);
485100435Simp
486100435Simp  Value *VisitBinLAnd       (const BinaryOperator *E);
487100435Simp  Value *VisitBinLOr        (const BinaryOperator *E);
48868218Smsmith  Value *VisitBinComma      (const BinaryOperator *E);
48968218Smsmith
49068218Smsmith  Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
49168218Smsmith  Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
49268218Smsmith
49368218Smsmith  // Other Operators.
49468218Smsmith  Value *VisitBlockExpr(const BlockExpr *BE);
49568218Smsmith  Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
496100435Simp  Value *VisitChooseExpr(ChooseExpr *CE);
49768218Smsmith  Value *VisitVAArgExpr(VAArgExpr *VE);
498100435Simp  Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
499100435Simp    return CGF.EmitObjCStringLiteral(E);
500100435Simp  }
501100435Simp  Value *VisitObjCNumericLiteral(ObjCNumericLiteral *E) {
502100435Simp    return CGF.EmitObjCNumericLiteral(E);
503100435Simp  }
50468218Smsmith  Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
505100435Simp    return CGF.EmitObjCArrayLiteral(E);
506100435Simp  }
507100435Simp  Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
508100435Simp    return CGF.EmitObjCDictionaryLiteral(E);
509100435Simp  }
510100435Simp  Value *VisitAsTypeExpr(AsTypeExpr *CE);
51168218Smsmith  Value *VisitAtomicExpr(AtomicExpr *AE);
51268218Smsmith};
513100435Simp}  // end anonymous namespace.
514100435Simp
515100435Simp//===----------------------------------------------------------------------===//
516100435Simp//                                Utilities
517100435Simp//===----------------------------------------------------------------------===//
518100435Simp
519100435Simp/// EmitConversionToBool - Convert the specified expression value to a
52068218Smsmith/// boolean (i1) truth value.  This is equivalent to "Val != 0".
521100435SimpValue *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
52268218Smsmith  assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
52368218Smsmith
524103017Sjhb  if (SrcType->isRealFloatingType())
525103017Sjhb    return EmitFloatToBoolConversion(Src);
526103017Sjhb
527103017Sjhb  if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
52868218Smsmith    return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
529103017Sjhb
530103017Sjhb  assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
531103017Sjhb         "Unknown scalar type to convert");
532103017Sjhb
533103017Sjhb  if (isa<llvm::IntegerType>(Src->getType()))
534103017Sjhb    return EmitIntToBoolConversion(Src);
535103017Sjhb
536103017Sjhb  assert(isa<llvm::PointerType>(Src->getType()));
537103017Sjhb  return EmitPointerToBoolConversion(Src);
538103017Sjhb}
539103017Sjhb
540103017Sjhb/// EmitScalarConversion - Emit a conversion from the specified type to the
541103017Sjhb/// specified destination type, both of which are LLVM scalar types.
542103017SjhbValue *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
543103017Sjhb                                               QualType DstType) {
54468218Smsmith  SrcType = CGF.getContext().getCanonicalType(SrcType);
545103017Sjhb  DstType = CGF.getContext().getCanonicalType(DstType);
546103017Sjhb  if (SrcType == DstType) return Src;
547103017Sjhb
548103017Sjhb  if (DstType->isVoidType()) return 0;
549103017Sjhb
550103017Sjhb  llvm::Type *SrcTy = Src->getType();
551103017Sjhb
552103017Sjhb  // Floating casts might be a bit special: if we're doing casts to / from half
553103017Sjhb  // FP, we should go via special intrinsics.
554103017Sjhb  if (SrcType->isHalfType()) {
555103017Sjhb    Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src);
556103017Sjhb    SrcType = CGF.getContext().FloatTy;
557103017Sjhb    SrcTy = CGF.FloatTy;
558103017Sjhb  }
559103017Sjhb
560103017Sjhb  // Handle conversions to bool first, they are special: comparisons against 0.
561103017Sjhb  if (DstType->isBooleanType())
562103017Sjhb    return EmitConversionToBool(Src, SrcType);
563103017Sjhb
564103017Sjhb  llvm::Type *DstTy = ConvertType(DstType);
565103017Sjhb
566103017Sjhb  // Ignore conversions like int -> uint.
567103017Sjhb  if (SrcTy == DstTy)
568103017Sjhb    return Src;
569103017Sjhb
570103017Sjhb  // Handle pointer conversions next: pointers can only be converted to/from
571103017Sjhb  // other pointers and integers. Check for pointer types in terms of LLVM, as
572103017Sjhb  // some native types (like Obj-C id) may map to a pointer type.
573103017Sjhb  if (isa<llvm::PointerType>(DstTy)) {
574103017Sjhb    // The source value may be an integer, or a pointer.
575103017Sjhb    if (isa<llvm::PointerType>(SrcTy))
57666529Smsmith      return Builder.CreateBitCast(Src, DstTy, "conv");
57766529Smsmith
57859294Smsmith    assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
57965176Sdfr    // First, convert to the correct width so that we control the kind of
58059294Smsmith    // extension.
581100435Simp    llvm::Type *MiddleTy = CGF.IntPtrTy;
582100435Simp    bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
58365304Speter    llvm::Value* IntResult =
584100435Simp        Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
585100435Simp    // Then, cast to pointer.
586100435Simp    return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
587100435Simp  }
588100435Simp
589100435Simp  if (isa<llvm::PointerType>(SrcTy)) {
590100435Simp    // Must be an ptr to int cast.
591100435Simp    assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
592100435Simp    return Builder.CreatePtrToInt(Src, DstTy, "conv");
593100435Simp  }
594100435Simp
595100435Simp  // A scalar can be splatted to an extended vector of the same element type
596100435Simp  if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
597100435Simp    // Cast the scalar to element type
598100435Simp    QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
599100435Simp    llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
600100435Simp
601100435Simp    // Insert the element in element zero of an undef vector
602100435Simp    llvm::Value *UnV = llvm::UndefValue::get(DstTy);
603100435Simp    llvm::Value *Idx = Builder.getInt32(0);
604100435Simp    UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
60559294Smsmith
60659294Smsmith    // Splat the element across to all elements
60759294Smsmith    unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
60865176Sdfr    llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements,
60959294Smsmith                                                          Builder.getInt32(0));
610100435Simp    llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
61165304Speter    return Yay;
612100435Simp  }
613100435Simp
614100435Simp  // Allow bitcast from vector to integer/fp of the same size.
615100435Simp  if (isa<llvm::VectorType>(SrcTy) ||
616100435Simp      isa<llvm::VectorType>(DstTy))
617100435Simp    return Builder.CreateBitCast(Src, DstTy, "conv");
618100435Simp
619100435Simp  // Finally, we have the arithmetic types: real int/float.
620100435Simp  Value *Res = NULL;
621100435Simp  llvm::Type *ResTy = DstTy;
622100435Simp
623100435Simp  // Cast to half via float
624100435Simp  if (DstType->isHalfType())
625100435Simp    DstTy = CGF.FloatTy;
626100435Simp
627100435Simp  if (isa<llvm::IntegerType>(SrcTy)) {
628100435Simp    bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
62959294Smsmith    if (isa<llvm::IntegerType>(DstTy))
63059294Smsmith      Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
63166529Smsmith    else if (InputSigned)
63266529Smsmith      Res = Builder.CreateSIToFP(Src, DstTy, "conv");
63366529Smsmith    else
63459294Smsmith      Res = Builder.CreateUIToFP(Src, DstTy, "conv");
63559294Smsmith  } else if (isa<llvm::IntegerType>(DstTy)) {
63659294Smsmith    assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
637100435Simp    if (DstType->isSignedIntegerOrEnumerationType())
63882035Simp      Res = Builder.CreateFPToSI(Src, DstTy, "conv");
639102976Sjhb    else
640100435Simp      Res = Builder.CreateFPToUI(Src, DstTy, "conv");
641100435Simp  } else {
642100435Simp    assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
643100435Simp           "Unknown real conversion");
644100435Simp    if (DstTy->getTypeID() < SrcTy->getTypeID())
645100435Simp      Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
64659294Smsmith    else
64759294Smsmith      Res = Builder.CreateFPExt(Src, DstTy, "conv");
64866529Smsmith  }
64966529Smsmith
65066529Smsmith  if (DstTy != ResTy) {
65159294Smsmith    assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
65226159Sse    Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res);
65310887Sse  }
65426159Sse
65526159Sse  return Res;
656100435Simp}
65710887Sse
658100435Simp/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
659100435Simp/// type to the specified destination type, where the destination type is an
660100435Simp/// LLVM scalar type.
661100435SimpValue *ScalarExprEmitter::
662100435SimpEmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
663100435Simp                              QualType SrcTy, QualType DstTy) {
664100435Simp  // Get the source element type.
665100435Simp  SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
666100435Simp
667100435Simp  // Handle conversions to bool first, they are special: comparisons against 0.
668100435Simp  if (DstTy->isBooleanType()) {
669100435Simp    //  Complex != 0  -> (Real != 0) | (Imag != 0)
670100435Simp    Src.first  = EmitScalarConversion(Src.first, SrcTy, DstTy);
671100435Simp    Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
672100435Simp    return Builder.CreateOr(Src.first, Src.second, "tobool");
673100435Simp  }
674100435Simp
675100435Simp  // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
676100435Simp  // the imaginary part of the complex value is discarded and the value of the
677100435Simp  // real part is converted according to the conversion rules for the
67826159Sse  // corresponding real type.
679100435Simp  return EmitScalarConversion(Src.first, SrcTy, DstTy);
68026159Sse}
6816104Sse
68226159SseValue *ScalarExprEmitter::EmitNullValue(QualType Ty) {
6836104Sse  if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
68426159Sse    return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
68526159Sse
686100435Simp  return llvm::Constant::getNullValue(ConvertType(Ty));
687100435Simp}
688100435Simp
689100435Simp//===----------------------------------------------------------------------===//
690100435Simp//                            Visitor Methods
691100435Simp//===----------------------------------------------------------------------===//
692100435Simp
693100435SimpValue *ScalarExprEmitter::VisitExpr(Expr *E) {
694100435Simp  CGF.ErrorUnsupported(E, "scalar expression");
69526159Sse  if (E->getType()->isVoidType())
6966104Sse    return 0;
69759294Smsmith  return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
69865176Sdfr}
69926159Sse
700100435SimpValue *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
701100435Simp  // Vector Mask Case
7027234Sse  if (E->getNumSubExprs() == 2 ||
703100435Simp      (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
7047234Sse    Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
705100435Simp    Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
706100435Simp    Value *Mask;
707100435Simp
708100435Simp    llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
709100435Simp    unsigned LHSElts = LTy->getNumElements();
710100435Simp
711100435Simp    if (E->getNumSubExprs() == 3) {
712100435Simp      Mask = CGF.EmitScalarExpr(E->getExpr(2));
713100435Simp
714100435Simp      // Shuffle LHS & RHS into one input vector.
715100435Simp      SmallVector<llvm::Constant*, 32> concat;
716100435Simp      for (unsigned i = 0; i != LHSElts; ++i) {
717100435Simp        concat.push_back(Builder.getInt32(2*i));
71826159Sse        concat.push_back(Builder.getInt32(2*i+1));
719100435Simp      }
72026159Sse
7217234Sse      Value* CV = llvm::ConstantVector::get(concat);
72259294Smsmith      LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
72365176Sdfr      LHSElts *= 2;
72426159Sse    } else {
725100435Simp      Mask = RHS;
7266104Sse    }
727100435Simp
728100435Simp    llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
729100435Simp    llvm::Constant* EltMask;
730100435Simp
731100435Simp    // Treat vec3 like vec4.
732100435Simp    if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
733100435Simp      EltMask = llvm::ConstantInt::get(MTy->getElementType(),
734100435Simp                                       (1 << llvm::Log2_32(LHSElts+2))-1);
735100435Simp    else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
736100435Simp      EltMask = llvm::ConstantInt::get(MTy->getElementType(),
737100435Simp                                       (1 << llvm::Log2_32(LHSElts+1))-1);
738100435Simp    else
739100435Simp      EltMask = llvm::ConstantInt::get(MTy->getElementType(),
740100435Simp                                       (1 << llvm::Log2_32(LHSElts))-1);
74126159Sse
74226159Sse    // Mask off the high bits of each shuffle index.
7436104Sse    Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
74466529Smsmith                                                     EltMask);
74510887Sse    Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
74626159Sse
74710887Sse    // newv = undef
748100435Simp    // mask = mask & maskbits
74910735Sse    // for each elt
75026159Sse    //   n = extract mask i
751100435Simp    //   x = extract val n
75210960Sse    //   newv = insert newv, x, i
753100435Simp    llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
754100435Simp                                                        MTy->getNumElements());
755100435Simp    Value* NewV = llvm::UndefValue::get(RTy);
756100435Simp    for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
75726159Sse      Value *IIndx = Builder.getInt32(i);
758100435Simp      Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
759100435Simp      Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
760100435Simp
76123415Sse      // Handle vec3 special since the index will be off by one for the RHS.
762100435Simp      if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
763100435Simp        Value *cmpIndx, *newIndx;
764100435Simp        cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
765100435Simp                                        "cmp_shuf_idx");
766100435Simp        newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
767100435Simp        Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
768100435Simp      }
769100435Simp      Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
770100435Simp      NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
771100435Simp    }
772100435Simp    return NewV;
773100435Simp  }
774100435Simp
775100435Simp  Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
776100435Simp  Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
777100435Simp
778100435Simp  // Handle vec3 special since the index will be off by one for the RHS.
779100435Simp  llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
78066529Smsmith  SmallVector<llvm::Constant*, 32> indices;
781100435Simp  for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
78223415Sse    unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
78366529Smsmith    if (VTy->getNumElements() == 3 && Idx > 3)
784100435Simp      Idx -= 1;
78510887Sse    indices.push_back(Builder.getInt32(Idx));
78610887Sse  }
78747307Speter
78859294Smsmith  Value *SV = llvm::ConstantVector::get(indices);
7896104Sse  return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
790100435Simp}
791100435SimpValue *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
7926104Sse  llvm::APSInt Value;
793100435Simp  if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
79410960Sse    if (E->isArrow())
795100435Simp      CGF.EmitScalarExpr(E->getBase());
796100435Simp    else
797100435Simp      EmitLValue(E->getBase());
798100435Simp    return Builder.getInt(Value);
79910960Sse  }
800100435Simp
80110960Sse  // Emit debug info for aggregate now, if it was delayed to reduce
802100435Simp  // debug info size.
803100435Simp  CGDebugInfo *DI = CGF.getDebugInfo();
80410960Sse  if (DI && CGF.CGM.getCodeGenOpts().LimitDebugInfo) {
805100435Simp    QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
806100435Simp    if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
807100435Simp      if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
808100435Simp        DI->getOrCreateRecordType(PTy->getPointeeType(),
80910960Sse                                  M->getParent()->getLocation());
810100435Simp  }
811100435Simp  return EmitLoadOfLValue(E);
812100435Simp}
8136104Sse
814100435SimpValue *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
815100435Simp  TestAndClearIgnoreResultAssign();
816100435Simp
817100435Simp  // Emit subscript expressions in rvalue context's.  For most cases, this just
81810807Sse  // loads the lvalue formed by the subscript expr.  However, we have to be
819100435Simp  // careful, because the base of a vector subscript is occasionally an rvalue,
820100435Simp  // so we can't get it as an lvalue.
821100435Simp  if (!E->getBase()->getType()->isVectorType())
82210887Sse    return EmitLoadOfLValue(E);
823100435Simp
824100435Simp  // Handle the vector case.  The base must be a vector, the index must be an
825100435Simp  // integer value.
82610887Sse  Value *Base = Visit(E->getBase());
827100435Simp  Value *Idx  = Visit(E->getIdx());
828100435Simp  bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType();
829100435Simp  Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
830100435Simp  return Builder.CreateExtractElement(Base, Idx, "vecext");
83111524Sse}
83211524Sse
833100435Simpstatic llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
83447307Speter                                  unsigned Off, llvm::Type *I32Ty) {
835100435Simp  int MV = SVI->getMaskValue(Idx);
836100435Simp  if (MV == -1)
837100435Simp    return llvm::UndefValue::get(I32Ty);
838100435Simp  return llvm::ConstantInt::get(I32Ty, Off+MV);
83947307Speter}
840100435Simp
84148832SmsmithValue *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
842100435Simp  bool Ignore = TestAndClearIgnoreResultAssign();
843100435Simp  (void)Ignore;
84448832Smsmith  assert (Ignore == false && "init list ignored");
845100435Simp  unsigned NumInitElements = E->getNumInits();
846100435Simp
847100435Simp  if (E->hadArrayRangeDesignator())
84848832Smsmith    CGF.ErrorUnsupported(E, "GNU array range designator extension");
849100435Simp
850100435Simp  llvm::VectorType *VType =
851100435Simp    dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
85252480Salc
853100435Simp  if (!VType) {
854100435Simp    if (NumInitElements == 0) {
855100435Simp      // C++11 value-initialization for the scalar.
85649404Speter      return EmitNullValue(E->getType());
857100435Simp    }
858100435Simp    // We have a scalar in braces. Just use the first element.
859100435Simp    return Visit(E->getInit(0));
86048832Smsmith  }
86148832Smsmith
862100435Simp  unsigned ResElts = VType->getNumElements();
863100435Simp
864100435Simp  // Loop over initializers collecting the Value for each, and remembering
86548832Smsmith  // whether the source was swizzle (ExtVectorElementExpr).  This will allow
86648832Smsmith  // us to fold the shuffle for the swizzle into the shuffle for the vector
867  // initializer, since LLVM optimizers generally do not want to touch
868  // shuffles.
869  unsigned CurIdx = 0;
870  bool VIsUndefShuffle = false;
871  llvm::Value *V = llvm::UndefValue::get(VType);
872  for (unsigned i = 0; i != NumInitElements; ++i) {
873    Expr *IE = E->getInit(i);
874    Value *Init = Visit(IE);
875    SmallVector<llvm::Constant*, 16> Args;
876
877    llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
878
879    // Handle scalar elements.  If the scalar initializer is actually one
880    // element of a different vector of the same width, use shuffle instead of
881    // extract+insert.
882    if (!VVT) {
883      if (isa<ExtVectorElementExpr>(IE)) {
884        llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
885
886        if (EI->getVectorOperandType()->getNumElements() == ResElts) {
887          llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
888          Value *LHS = 0, *RHS = 0;
889          if (CurIdx == 0) {
890            // insert into undef -> shuffle (src, undef)
891            Args.push_back(C);
892            Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
893
894            LHS = EI->getVectorOperand();
895            RHS = V;
896            VIsUndefShuffle = true;
897          } else if (VIsUndefShuffle) {
898            // insert into undefshuffle && size match -> shuffle (v, src)
899            llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
900            for (unsigned j = 0; j != CurIdx; ++j)
901              Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
902            Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
903            Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
904
905            LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
906            RHS = EI->getVectorOperand();
907            VIsUndefShuffle = false;
908          }
909          if (!Args.empty()) {
910            llvm::Constant *Mask = llvm::ConstantVector::get(Args);
911            V = Builder.CreateShuffleVector(LHS, RHS, Mask);
912            ++CurIdx;
913            continue;
914          }
915        }
916      }
917      V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
918                                      "vecinit");
919      VIsUndefShuffle = false;
920      ++CurIdx;
921      continue;
922    }
923
924    unsigned InitElts = VVT->getNumElements();
925
926    // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
927    // input is the same width as the vector being constructed, generate an
928    // optimized shuffle of the swizzle input into the result.
929    unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
930    if (isa<ExtVectorElementExpr>(IE)) {
931      llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
932      Value *SVOp = SVI->getOperand(0);
933      llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
934
935      if (OpTy->getNumElements() == ResElts) {
936        for (unsigned j = 0; j != CurIdx; ++j) {
937          // If the current vector initializer is a shuffle with undef, merge
938          // this shuffle directly into it.
939          if (VIsUndefShuffle) {
940            Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
941                                      CGF.Int32Ty));
942          } else {
943            Args.push_back(Builder.getInt32(j));
944          }
945        }
946        for (unsigned j = 0, je = InitElts; j != je; ++j)
947          Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
948        Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
949
950        if (VIsUndefShuffle)
951          V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
952
953        Init = SVOp;
954      }
955    }
956
957    // Extend init to result vector length, and then shuffle its contribution
958    // to the vector initializer into V.
959    if (Args.empty()) {
960      for (unsigned j = 0; j != InitElts; ++j)
961        Args.push_back(Builder.getInt32(j));
962      Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
963      llvm::Constant *Mask = llvm::ConstantVector::get(Args);
964      Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
965                                         Mask, "vext");
966
967      Args.clear();
968      for (unsigned j = 0; j != CurIdx; ++j)
969        Args.push_back(Builder.getInt32(j));
970      for (unsigned j = 0; j != InitElts; ++j)
971        Args.push_back(Builder.getInt32(j+Offset));
972      Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
973    }
974
975    // If V is undef, make sure it ends up on the RHS of the shuffle to aid
976    // merging subsequent shuffles into this one.
977    if (CurIdx == 0)
978      std::swap(V, Init);
979    llvm::Constant *Mask = llvm::ConstantVector::get(Args);
980    V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
981    VIsUndefShuffle = isa<llvm::UndefValue>(Init);
982    CurIdx += InitElts;
983  }
984
985  // FIXME: evaluate codegen vs. shuffling against constant null vector.
986  // Emit remaining default initializers.
987  llvm::Type *EltTy = VType->getElementType();
988
989  // Emit remaining default initializers
990  for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
991    Value *Idx = Builder.getInt32(CurIdx);
992    llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
993    V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
994  }
995  return V;
996}
997
998static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
999  const Expr *E = CE->getSubExpr();
1000
1001  if (CE->getCastKind() == CK_UncheckedDerivedToBase)
1002    return false;
1003
1004  if (isa<CXXThisExpr>(E)) {
1005    // We always assume that 'this' is never null.
1006    return false;
1007  }
1008
1009  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
1010    // And that glvalue casts are never null.
1011    if (ICE->getValueKind() != VK_RValue)
1012      return false;
1013  }
1014
1015  return true;
1016}
1017
1018// VisitCastExpr - Emit code for an explicit or implicit cast.  Implicit casts
1019// have to handle a more broad range of conversions than explicit casts, as they
1020// handle things like function to ptr-to-function decay etc.
1021Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
1022  Expr *E = CE->getSubExpr();
1023  QualType DestTy = CE->getType();
1024  CastKind Kind = CE->getCastKind();
1025
1026  if (!DestTy->isVoidType())
1027    TestAndClearIgnoreResultAssign();
1028
1029  // Since almost all cast kinds apply to scalars, this switch doesn't have
1030  // a default case, so the compiler will warn on a missing case.  The cases
1031  // are in the same order as in the CastKind enum.
1032  switch (Kind) {
1033  case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1034
1035  case CK_LValueBitCast:
1036  case CK_ObjCObjectLValueCast: {
1037    Value *V = EmitLValue(E).getAddress();
1038    V = Builder.CreateBitCast(V,
1039                          ConvertType(CGF.getContext().getPointerType(DestTy)));
1040    return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy));
1041  }
1042
1043  case CK_CPointerToObjCPointerCast:
1044  case CK_BlockPointerToObjCPointerCast:
1045  case CK_AnyPointerToBlockPointerCast:
1046  case CK_BitCast: {
1047    Value *Src = Visit(const_cast<Expr*>(E));
1048    return Builder.CreateBitCast(Src, ConvertType(DestTy));
1049  }
1050  case CK_AtomicToNonAtomic:
1051  case CK_NonAtomicToAtomic:
1052  case CK_NoOp:
1053  case CK_UserDefinedConversion:
1054    return Visit(const_cast<Expr*>(E));
1055
1056  case CK_BaseToDerived: {
1057    const CXXRecordDecl *DerivedClassDecl =
1058      DestTy->getCXXRecordDeclForPointerType();
1059
1060    return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
1061                                        CE->path_begin(), CE->path_end(),
1062                                        ShouldNullCheckClassCastValue(CE));
1063  }
1064  case CK_UncheckedDerivedToBase:
1065  case CK_DerivedToBase: {
1066    const RecordType *DerivedClassTy =
1067      E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
1068    CXXRecordDecl *DerivedClassDecl =
1069      cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1070
1071    return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
1072                                     CE->path_begin(), CE->path_end(),
1073                                     ShouldNullCheckClassCastValue(CE));
1074  }
1075  case CK_Dynamic: {
1076    Value *V = Visit(const_cast<Expr*>(E));
1077    const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1078    return CGF.EmitDynamicCast(V, DCE);
1079  }
1080
1081  case CK_ArrayToPointerDecay: {
1082    assert(E->getType()->isArrayType() &&
1083           "Array to pointer decay must have array source type!");
1084
1085    Value *V = EmitLValue(E).getAddress();  // Bitfields can't be arrays.
1086
1087    // Note that VLA pointers are always decayed, so we don't need to do
1088    // anything here.
1089    if (!E->getType()->isVariableArrayType()) {
1090      assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1091      assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1092                                 ->getElementType()) &&
1093             "Expected pointer to array");
1094      V = Builder.CreateStructGEP(V, 0, "arraydecay");
1095    }
1096
1097    // Make sure the array decay ends up being the right type.  This matters if
1098    // the array type was of an incomplete type.
1099    return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType()));
1100  }
1101  case CK_FunctionToPointerDecay:
1102    return EmitLValue(E).getAddress();
1103
1104  case CK_NullToPointer:
1105    if (MustVisitNullValue(E))
1106      (void) Visit(E);
1107
1108    return llvm::ConstantPointerNull::get(
1109                               cast<llvm::PointerType>(ConvertType(DestTy)));
1110
1111  case CK_NullToMemberPointer: {
1112    if (MustVisitNullValue(E))
1113      (void) Visit(E);
1114
1115    const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1116    return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1117  }
1118
1119  case CK_ReinterpretMemberPointer:
1120  case CK_BaseToDerivedMemberPointer:
1121  case CK_DerivedToBaseMemberPointer: {
1122    Value *Src = Visit(E);
1123
1124    // Note that the AST doesn't distinguish between checked and
1125    // unchecked member pointer conversions, so we always have to
1126    // implement checked conversions here.  This is inefficient when
1127    // actual control flow may be required in order to perform the
1128    // check, which it is for data member pointers (but not member
1129    // function pointers on Itanium and ARM).
1130    return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
1131  }
1132
1133  case CK_ARCProduceObject:
1134    return CGF.EmitARCRetainScalarExpr(E);
1135  case CK_ARCConsumeObject:
1136    return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
1137  case CK_ARCReclaimReturnedObject: {
1138    llvm::Value *value = Visit(E);
1139    value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1140    return CGF.EmitObjCConsumeObject(E->getType(), value);
1141  }
1142  case CK_ARCExtendBlockObject:
1143    return CGF.EmitARCExtendBlockObject(E);
1144
1145  case CK_CopyAndAutoreleaseBlockObject:
1146    return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
1147
1148  case CK_FloatingRealToComplex:
1149  case CK_FloatingComplexCast:
1150  case CK_IntegralRealToComplex:
1151  case CK_IntegralComplexCast:
1152  case CK_IntegralComplexToFloatingComplex:
1153  case CK_FloatingComplexToIntegralComplex:
1154  case CK_ConstructorConversion:
1155  case CK_ToUnion:
1156    llvm_unreachable("scalar cast to non-scalar value");
1157
1158  case CK_LValueToRValue:
1159    assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
1160    assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
1161    return Visit(const_cast<Expr*>(E));
1162
1163  case CK_IntegralToPointer: {
1164    Value *Src = Visit(const_cast<Expr*>(E));
1165
1166    // First, convert to the correct width so that we control the kind of
1167    // extension.
1168    llvm::Type *MiddleTy = CGF.IntPtrTy;
1169    bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
1170    llvm::Value* IntResult =
1171      Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1172
1173    return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
1174  }
1175  case CK_PointerToIntegral:
1176    assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1177    return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
1178
1179  case CK_ToVoid: {
1180    CGF.EmitIgnoredExpr(E);
1181    return 0;
1182  }
1183  case CK_VectorSplat: {
1184    llvm::Type *DstTy = ConvertType(DestTy);
1185    Value *Elt = Visit(const_cast<Expr*>(E));
1186    Elt = EmitScalarConversion(Elt, E->getType(),
1187                               DestTy->getAs<VectorType>()->getElementType());
1188
1189    // Insert the element in element zero of an undef vector
1190    llvm::Value *UnV = llvm::UndefValue::get(DstTy);
1191    llvm::Value *Idx = Builder.getInt32(0);
1192    UnV = Builder.CreateInsertElement(UnV, Elt, Idx);
1193
1194    // Splat the element across to all elements
1195    unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
1196    llvm::Constant *Zero = Builder.getInt32(0);
1197    llvm::Constant *Mask = llvm::ConstantVector::getSplat(NumElements, Zero);
1198    llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1199    return Yay;
1200  }
1201
1202  case CK_IntegralCast:
1203  case CK_IntegralToFloating:
1204  case CK_FloatingToIntegral:
1205  case CK_FloatingCast:
1206    return EmitScalarConversion(Visit(E), E->getType(), DestTy);
1207  case CK_IntegralToBoolean:
1208    return EmitIntToBoolConversion(Visit(E));
1209  case CK_PointerToBoolean:
1210    return EmitPointerToBoolConversion(Visit(E));
1211  case CK_FloatingToBoolean:
1212    return EmitFloatToBoolConversion(Visit(E));
1213  case CK_MemberPointerToBoolean: {
1214    llvm::Value *MemPtr = Visit(E);
1215    const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1216    return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
1217  }
1218
1219  case CK_FloatingComplexToReal:
1220  case CK_IntegralComplexToReal:
1221    return CGF.EmitComplexExpr(E, false, true).first;
1222
1223  case CK_FloatingComplexToBoolean:
1224  case CK_IntegralComplexToBoolean: {
1225    CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
1226
1227    // TODO: kill this function off, inline appropriate case here
1228    return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1229  }
1230
1231  }
1232
1233  llvm_unreachable("unknown scalar cast");
1234}
1235
1236Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
1237  CodeGenFunction::StmtExprEvaluation eval(CGF);
1238  return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1239    .getScalarVal();
1240}
1241
1242//===----------------------------------------------------------------------===//
1243//                             Unary Operators
1244//===----------------------------------------------------------------------===//
1245
1246llvm::Value *ScalarExprEmitter::
1247EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1248                                llvm::Value *InVal,
1249                                llvm::Value *NextVal, bool IsInc) {
1250  switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
1251  case LangOptions::SOB_Undefined:
1252    return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1253  case LangOptions::SOB_Defined:
1254    return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1255  case LangOptions::SOB_Trapping:
1256    BinOpInfo BinOp;
1257    BinOp.LHS = InVal;
1258    BinOp.RHS = NextVal;
1259    BinOp.Ty = E->getType();
1260    BinOp.Opcode = BO_Add;
1261    BinOp.E = E;
1262    return EmitOverflowCheckedBinOp(BinOp);
1263  }
1264  llvm_unreachable("Unknown SignedOverflowBehaviorTy");
1265}
1266
1267llvm::Value *
1268ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1269                                           bool isInc, bool isPre) {
1270
1271  QualType type = E->getSubExpr()->getType();
1272  llvm::Value *value = EmitLoadOfLValue(LV);
1273  llvm::Value *input = value;
1274  llvm::PHINode *atomicPHI = 0;
1275
1276  int amount = (isInc ? 1 : -1);
1277
1278  if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
1279    llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1280    llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1281    Builder.CreateBr(opBB);
1282    Builder.SetInsertPoint(opBB);
1283    atomicPHI = Builder.CreatePHI(value->getType(), 2);
1284    atomicPHI->addIncoming(value, startBB);
1285    type = atomicTy->getValueType();
1286    value = atomicPHI;
1287  }
1288
1289  // Special case of integer increment that we have to check first: bool++.
1290  // Due to promotion rules, we get:
1291  //   bool++ -> bool = bool + 1
1292  //          -> bool = (int)bool + 1
1293  //          -> bool = ((int)bool + 1 != 0)
1294  // An interesting aspect of this is that increment is always true.
1295  // Decrement does not have this property.
1296  if (isInc && type->isBooleanType()) {
1297    value = Builder.getTrue();
1298
1299  // Most common case by far: integer increment.
1300  } else if (type->isIntegerType()) {
1301
1302    llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1303
1304    // Note that signed integer inc/dec with width less than int can't
1305    // overflow because of promotion rules; we're just eliding a few steps here.
1306    if (type->isSignedIntegerOrEnumerationType() &&
1307        value->getType()->getPrimitiveSizeInBits() >=
1308            CGF.IntTy->getBitWidth())
1309      value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
1310    else
1311      value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1312
1313  // Next most common: pointer increment.
1314  } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1315    QualType type = ptr->getPointeeType();
1316
1317    // VLA types don't have constant size.
1318    if (const VariableArrayType *vla
1319          = CGF.getContext().getAsVariableArrayType(type)) {
1320      llvm::Value *numElts = CGF.getVLASize(vla).first;
1321      if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
1322      if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
1323        value = Builder.CreateGEP(value, numElts, "vla.inc");
1324      else
1325        value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
1326
1327    // Arithmetic on function pointers (!) is just +-1.
1328    } else if (type->isFunctionType()) {
1329      llvm::Value *amt = Builder.getInt32(amount);
1330
1331      value = CGF.EmitCastToVoidPtr(value);
1332      if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
1333        value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1334      else
1335        value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
1336      value = Builder.CreateBitCast(value, input->getType());
1337
1338    // For everything else, we can just do a simple increment.
1339    } else {
1340      llvm::Value *amt = Builder.getInt32(amount);
1341      if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
1342        value = Builder.CreateGEP(value, amt, "incdec.ptr");
1343      else
1344        value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
1345    }
1346
1347  // Vector increment/decrement.
1348  } else if (type->isVectorType()) {
1349    if (type->hasIntegerRepresentation()) {
1350      llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1351
1352      value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1353    } else {
1354      value = Builder.CreateFAdd(
1355                  value,
1356                  llvm::ConstantFP::get(value->getType(), amount),
1357                  isInc ? "inc" : "dec");
1358    }
1359
1360  // Floating point.
1361  } else if (type->isRealFloatingType()) {
1362    // Add the inc/dec to the real part.
1363    llvm::Value *amt;
1364
1365    if (type->isHalfType()) {
1366      // Another special case: half FP increment should be done via float
1367      value =
1368    Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16),
1369                       input);
1370    }
1371
1372    if (value->getType()->isFloatTy())
1373      amt = llvm::ConstantFP::get(VMContext,
1374                                  llvm::APFloat(static_cast<float>(amount)));
1375    else if (value->getType()->isDoubleTy())
1376      amt = llvm::ConstantFP::get(VMContext,
1377                                  llvm::APFloat(static_cast<double>(amount)));
1378    else {
1379      llvm::APFloat F(static_cast<float>(amount));
1380      bool ignored;
1381      F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1382                &ignored);
1383      amt = llvm::ConstantFP::get(VMContext, F);
1384    }
1385    value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1386
1387    if (type->isHalfType())
1388      value =
1389       Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16),
1390                          value);
1391
1392  // Objective-C pointer types.
1393  } else {
1394    const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1395    value = CGF.EmitCastToVoidPtr(value);
1396
1397    CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1398    if (!isInc) size = -size;
1399    llvm::Value *sizeValue =
1400      llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1401
1402    if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
1403      value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1404    else
1405      value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
1406    value = Builder.CreateBitCast(value, input->getType());
1407  }
1408
1409  if (atomicPHI) {
1410    llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1411    llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1412    llvm::Value *old = Builder.CreateAtomicCmpXchg(LV.getAddress(), atomicPHI,
1413        value, llvm::SequentiallyConsistent);
1414    atomicPHI->addIncoming(old, opBB);
1415    llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1416    Builder.CreateCondBr(success, contBB, opBB);
1417    Builder.SetInsertPoint(contBB);
1418    return isPre ? value : input;
1419  }
1420
1421  // Store the updated result through the lvalue.
1422  if (LV.isBitField())
1423    CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
1424  else
1425    CGF.EmitStoreThroughLValue(RValue::get(value), LV);
1426
1427  // If this is a postinc, return the value read from memory, otherwise use the
1428  // updated value.
1429  return isPre ? value : input;
1430}
1431
1432
1433
1434Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
1435  TestAndClearIgnoreResultAssign();
1436  // Emit unary minus with EmitSub so we handle overflow cases etc.
1437  BinOpInfo BinOp;
1438  BinOp.RHS = Visit(E->getSubExpr());
1439
1440  if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1441    BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1442  else
1443    BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
1444  BinOp.Ty = E->getType();
1445  BinOp.Opcode = BO_Sub;
1446  BinOp.E = E;
1447  return EmitSub(BinOp);
1448}
1449
1450Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
1451  TestAndClearIgnoreResultAssign();
1452  Value *Op = Visit(E->getSubExpr());
1453  return Builder.CreateNot(Op, "neg");
1454}
1455
1456Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1457
1458  // Perform vector logical not on comparison with zero vector.
1459  if (E->getType()->isExtVectorType()) {
1460    Value *Oper = Visit(E->getSubExpr());
1461    Value *Zero = llvm::Constant::getNullValue(Oper->getType());
1462    Value *Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
1463    return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1464  }
1465
1466  // Compare operand to zero.
1467  Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
1468
1469  // Invert value.
1470  // TODO: Could dynamically modify easy computations here.  For example, if
1471  // the operand is an icmp ne, turn into icmp eq.
1472  BoolVal = Builder.CreateNot(BoolVal, "lnot");
1473
1474  // ZExt result to the expr type.
1475  return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
1476}
1477
1478Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1479  // Try folding the offsetof to a constant.
1480  llvm::APSInt Value;
1481  if (E->EvaluateAsInt(Value, CGF.getContext()))
1482    return Builder.getInt(Value);
1483
1484  // Loop over the components of the offsetof to compute the value.
1485  unsigned n = E->getNumComponents();
1486  llvm::Type* ResultType = ConvertType(E->getType());
1487  llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1488  QualType CurrentType = E->getTypeSourceInfo()->getType();
1489  for (unsigned i = 0; i != n; ++i) {
1490    OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
1491    llvm::Value *Offset = 0;
1492    switch (ON.getKind()) {
1493    case OffsetOfExpr::OffsetOfNode::Array: {
1494      // Compute the index
1495      Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1496      llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
1497      bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
1498      Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1499
1500      // Save the element type
1501      CurrentType =
1502          CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1503
1504      // Compute the element size
1505      llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1506          CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1507
1508      // Multiply out to compute the result
1509      Offset = Builder.CreateMul(Idx, ElemSize);
1510      break;
1511    }
1512
1513    case OffsetOfExpr::OffsetOfNode::Field: {
1514      FieldDecl *MemberDecl = ON.getField();
1515      RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1516      const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1517
1518      // Compute the index of the field in its parent.
1519      unsigned i = 0;
1520      // FIXME: It would be nice if we didn't have to loop here!
1521      for (RecordDecl::field_iterator Field = RD->field_begin(),
1522                                      FieldEnd = RD->field_end();
1523           Field != FieldEnd; (void)++Field, ++i) {
1524        if (*Field == MemberDecl)
1525          break;
1526      }
1527      assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1528
1529      // Compute the offset to the field
1530      int64_t OffsetInt = RL.getFieldOffset(i) /
1531                          CGF.getContext().getCharWidth();
1532      Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1533
1534      // Save the element type.
1535      CurrentType = MemberDecl->getType();
1536      break;
1537    }
1538
1539    case OffsetOfExpr::OffsetOfNode::Identifier:
1540      llvm_unreachable("dependent __builtin_offsetof");
1541
1542    case OffsetOfExpr::OffsetOfNode::Base: {
1543      if (ON.getBase()->isVirtual()) {
1544        CGF.ErrorUnsupported(E, "virtual base in offsetof");
1545        continue;
1546      }
1547
1548      RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1549      const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1550
1551      // Save the element type.
1552      CurrentType = ON.getBase()->getType();
1553
1554      // Compute the offset to the base.
1555      const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1556      CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
1557      int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) /
1558                          CGF.getContext().getCharWidth();
1559      Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1560      break;
1561    }
1562    }
1563    Result = Builder.CreateAdd(Result, Offset);
1564  }
1565  return Result;
1566}
1567
1568/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
1569/// argument of the sizeof expression as an integer.
1570Value *
1571ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1572                              const UnaryExprOrTypeTraitExpr *E) {
1573  QualType TypeToSize = E->getTypeOfArgument();
1574  if (E->getKind() == UETT_SizeOf) {
1575    if (const VariableArrayType *VAT =
1576          CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1577      if (E->isArgumentType()) {
1578        // sizeof(type) - make sure to emit the VLA size.
1579        CGF.EmitVariablyModifiedType(TypeToSize);
1580      } else {
1581        // C99 6.5.3.4p2: If the argument is an expression of type
1582        // VLA, it is evaluated.
1583        CGF.EmitIgnoredExpr(E->getArgumentExpr());
1584      }
1585
1586      QualType eltType;
1587      llvm::Value *numElts;
1588      llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
1589
1590      llvm::Value *size = numElts;
1591
1592      // Scale the number of non-VLA elements by the non-VLA element size.
1593      CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1594      if (!eltSize.isOne())
1595        size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1596
1597      return size;
1598    }
1599  }
1600
1601  // If this isn't sizeof(vla), the result must be constant; use the constant
1602  // folding logic so we don't have to duplicate it here.
1603  return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
1604}
1605
1606Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1607  Expr *Op = E->getSubExpr();
1608  if (Op->getType()->isAnyComplexType()) {
1609    // If it's an l-value, load through the appropriate subobject l-value.
1610    // Note that we have to ask E because Op might be an l-value that
1611    // this won't work for, e.g. an Obj-C property.
1612    if (E->isGLValue())
1613      return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
1614
1615    // Otherwise, calculate and project.
1616    return CGF.EmitComplexExpr(Op, false, true).first;
1617  }
1618
1619  return Visit(Op);
1620}
1621
1622Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1623  Expr *Op = E->getSubExpr();
1624  if (Op->getType()->isAnyComplexType()) {
1625    // If it's an l-value, load through the appropriate subobject l-value.
1626    // Note that we have to ask E because Op might be an l-value that
1627    // this won't work for, e.g. an Obj-C property.
1628    if (Op->isGLValue())
1629      return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
1630
1631    // Otherwise, calculate and project.
1632    return CGF.EmitComplexExpr(Op, true, false).second;
1633  }
1634
1635  // __imag on a scalar returns zero.  Emit the subexpr to ensure side
1636  // effects are evaluated, but not the actual value.
1637  if (Op->isGLValue())
1638    CGF.EmitLValue(Op);
1639  else
1640    CGF.EmitScalarExpr(Op, true);
1641  return llvm::Constant::getNullValue(ConvertType(E->getType()));
1642}
1643
1644//===----------------------------------------------------------------------===//
1645//                           Binary Operators
1646//===----------------------------------------------------------------------===//
1647
1648BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
1649  TestAndClearIgnoreResultAssign();
1650  BinOpInfo Result;
1651  Result.LHS = Visit(E->getLHS());
1652  Result.RHS = Visit(E->getRHS());
1653  Result.Ty  = E->getType();
1654  Result.Opcode = E->getOpcode();
1655  Result.E = E;
1656  return Result;
1657}
1658
1659LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1660                                              const CompoundAssignOperator *E,
1661                        Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
1662                                                   Value *&Result) {
1663  QualType LHSTy = E->getLHS()->getType();
1664  BinOpInfo OpInfo;
1665
1666  if (E->getComputationResultType()->isAnyComplexType()) {
1667    // This needs to go through the complex expression emitter, but it's a tad
1668    // complicated to do that... I'm leaving it out for now.  (Note that we do
1669    // actually need the imaginary part of the RHS for multiplication and
1670    // division.)
1671    CGF.ErrorUnsupported(E, "complex compound assignment");
1672    Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
1673    return LValue();
1674  }
1675
1676  // Emit the RHS first.  __block variables need to have the rhs evaluated
1677  // first, plus this should improve codegen a little.
1678  OpInfo.RHS = Visit(E->getRHS());
1679  OpInfo.Ty = E->getComputationResultType();
1680  OpInfo.Opcode = E->getOpcode();
1681  OpInfo.E = E;
1682  // Load/convert the LHS.
1683  LValue LHSLV = EmitCheckedLValue(E->getLHS());
1684  OpInfo.LHS = EmitLoadOfLValue(LHSLV);
1685  OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1686                                    E->getComputationLHSType());
1687
1688  llvm::PHINode *atomicPHI = 0;
1689  if (const AtomicType *atomicTy = OpInfo.Ty->getAs<AtomicType>()) {
1690    // FIXME: For floating point types, we should be saving and restoring the
1691    // floating point environment in the loop.
1692    llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1693    llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1694    Builder.CreateBr(opBB);
1695    Builder.SetInsertPoint(opBB);
1696    atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
1697    atomicPHI->addIncoming(OpInfo.LHS, startBB);
1698    OpInfo.Ty = atomicTy->getValueType();
1699    OpInfo.LHS = atomicPHI;
1700  }
1701
1702  // Expand the binary operator.
1703  Result = (this->*Func)(OpInfo);
1704
1705  // Convert the result back to the LHS type.
1706  Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
1707
1708  if (atomicPHI) {
1709    llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1710    llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1711    llvm::Value *old = Builder.CreateAtomicCmpXchg(LHSLV.getAddress(), atomicPHI,
1712        Result, llvm::SequentiallyConsistent);
1713    atomicPHI->addIncoming(old, opBB);
1714    llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1715    Builder.CreateCondBr(success, contBB, opBB);
1716    Builder.SetInsertPoint(contBB);
1717    return LHSLV;
1718  }
1719
1720  // Store the result value into the LHS lvalue. Bit-fields are handled
1721  // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1722  // 'An assignment expression has the value of the left operand after the
1723  // assignment...'.
1724  if (LHSLV.isBitField())
1725    CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
1726  else
1727    CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
1728
1729  return LHSLV;
1730}
1731
1732Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1733                      Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1734  bool Ignore = TestAndClearIgnoreResultAssign();
1735  Value *RHS;
1736  LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1737
1738  // If the result is clearly ignored, return now.
1739  if (Ignore)
1740    return 0;
1741
1742  // The result of an assignment in C is the assigned r-value.
1743  if (!CGF.getContext().getLangOpts().CPlusPlus)
1744    return RHS;
1745
1746  // If the lvalue is non-volatile, return the computed value of the assignment.
1747  if (!LHS.isVolatileQualified())
1748    return RHS;
1749
1750  // Otherwise, reload the value.
1751  return EmitLoadOfLValue(LHS);
1752}
1753
1754void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
1755     					    const BinOpInfo &Ops,
1756				     	    llvm::Value *Zero, bool isDiv) {
1757  llvm::Function::iterator insertPt = Builder.GetInsertBlock();
1758  llvm::BasicBlock *contBB =
1759    CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn,
1760                         llvm::next(insertPt));
1761  llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1762
1763  llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
1764
1765  if (Ops.Ty->hasSignedIntegerRepresentation()) {
1766    llvm::Value *IntMin =
1767      Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
1768    llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1769
1770    llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero);
1771    llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin);
1772    llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne);
1773    llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and");
1774    Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"),
1775                         overflowBB, contBB);
1776  } else {
1777    CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero),
1778                             overflowBB, contBB);
1779  }
1780  EmitOverflowBB(overflowBB);
1781  Builder.SetInsertPoint(contBB);
1782}
1783
1784Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
1785  if (isTrapvOverflowBehavior()) {
1786    llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1787
1788    if (Ops.Ty->isIntegerType())
1789      EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
1790    else if (Ops.Ty->isRealFloatingType()) {
1791      llvm::Function::iterator insertPt = Builder.GetInsertBlock();
1792      llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn,
1793                                                       llvm::next(insertPt));
1794      llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow",
1795                                                          CGF.CurFn);
1796      CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero),
1797                               overflowBB, DivCont);
1798      EmitOverflowBB(overflowBB);
1799      Builder.SetInsertPoint(DivCont);
1800    }
1801  }
1802  if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
1803    llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
1804    if (CGF.getContext().getLangOpts().OpenCL) {
1805      // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
1806      llvm::Type *ValTy = Val->getType();
1807      if (ValTy->isFloatTy() ||
1808          (isa<llvm::VectorType>(ValTy) &&
1809           cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
1810        CGF.SetFPAccuracy(Val, 2.5);
1811    }
1812    return Val;
1813  }
1814  else if (Ops.Ty->hasUnsignedIntegerRepresentation())
1815    return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1816  else
1817    return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1818}
1819
1820Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1821  // Rem in C can't be a floating point type: C99 6.5.5p2.
1822  if (isTrapvOverflowBehavior()) {
1823    llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1824
1825    if (Ops.Ty->isIntegerType())
1826      EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1827  }
1828
1829  if (Ops.Ty->hasUnsignedIntegerRepresentation())
1830    return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1831  else
1832    return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1833}
1834
1835Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1836  unsigned IID;
1837  unsigned OpID = 0;
1838
1839  switch (Ops.Opcode) {
1840  case BO_Add:
1841  case BO_AddAssign:
1842    OpID = 1;
1843    IID = llvm::Intrinsic::sadd_with_overflow;
1844    break;
1845  case BO_Sub:
1846  case BO_SubAssign:
1847    OpID = 2;
1848    IID = llvm::Intrinsic::ssub_with_overflow;
1849    break;
1850  case BO_Mul:
1851  case BO_MulAssign:
1852    OpID = 3;
1853    IID = llvm::Intrinsic::smul_with_overflow;
1854    break;
1855  default:
1856    llvm_unreachable("Unsupported operation for overflow detection");
1857  }
1858  OpID <<= 1;
1859  OpID |= 1;
1860
1861  llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1862
1863  llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
1864
1865  Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1866  Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1867  Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1868
1869  // Branch in case of overflow.
1870  llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
1871  llvm::Function::iterator insertPt = initialBB;
1872  llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
1873                                                      llvm::next(insertPt));
1874  llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1875
1876  Builder.CreateCondBr(overflow, overflowBB, continueBB);
1877
1878  // Handle overflow with llvm.trap.
1879  const std::string *handlerName =
1880    &CGF.getContext().getLangOpts().OverflowHandler;
1881  if (handlerName->empty()) {
1882    EmitOverflowBB(overflowBB);
1883    Builder.SetInsertPoint(continueBB);
1884    return result;
1885  }
1886
1887  // If an overflow handler is set, then we want to call it and then use its
1888  // result, if it returns.
1889  Builder.SetInsertPoint(overflowBB);
1890
1891  // Get the overflow handler.
1892  llvm::Type *Int8Ty = CGF.Int8Ty;
1893  llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
1894  llvm::FunctionType *handlerTy =
1895      llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
1896  llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
1897
1898  // Sign extend the args to 64-bit, so that we can use the same handler for
1899  // all types of overflow.
1900  llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
1901  llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
1902
1903  // Call the handler with the two arguments, the operation, and the size of
1904  // the result.
1905  llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
1906      Builder.getInt8(OpID),
1907      Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
1908
1909  // Truncate the result back to the desired size.
1910  handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1911  Builder.CreateBr(continueBB);
1912
1913  Builder.SetInsertPoint(continueBB);
1914  llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
1915  phi->addIncoming(result, initialBB);
1916  phi->addIncoming(handlerResult, overflowBB);
1917
1918  return phi;
1919}
1920
1921/// Emit pointer + index arithmetic.
1922static Value *emitPointerArithmetic(CodeGenFunction &CGF,
1923                                    const BinOpInfo &op,
1924                                    bool isSubtraction) {
1925  // Must have binary (not unary) expr here.  Unary pointer
1926  // increment/decrement doesn't use this path.
1927  const BinaryOperator *expr = cast<BinaryOperator>(op.E);
1928
1929  Value *pointer = op.LHS;
1930  Expr *pointerOperand = expr->getLHS();
1931  Value *index = op.RHS;
1932  Expr *indexOperand = expr->getRHS();
1933
1934  // In a subtraction, the LHS is always the pointer.
1935  if (!isSubtraction && !pointer->getType()->isPointerTy()) {
1936    std::swap(pointer, index);
1937    std::swap(pointerOperand, indexOperand);
1938  }
1939
1940  unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
1941  if (width != CGF.PointerWidthInBits) {
1942    // Zero-extend or sign-extend the pointer value according to
1943    // whether the index is signed or not.
1944    bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
1945    index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
1946                                      "idx.ext");
1947  }
1948
1949  // If this is subtraction, negate the index.
1950  if (isSubtraction)
1951    index = CGF.Builder.CreateNeg(index, "idx.neg");
1952
1953  const PointerType *pointerType
1954    = pointerOperand->getType()->getAs<PointerType>();
1955  if (!pointerType) {
1956    QualType objectType = pointerOperand->getType()
1957                                        ->castAs<ObjCObjectPointerType>()
1958                                        ->getPointeeType();
1959    llvm::Value *objectSize
1960      = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
1961
1962    index = CGF.Builder.CreateMul(index, objectSize);
1963
1964    Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1965    result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1966    return CGF.Builder.CreateBitCast(result, pointer->getType());
1967  }
1968
1969  QualType elementType = pointerType->getPointeeType();
1970  if (const VariableArrayType *vla
1971        = CGF.getContext().getAsVariableArrayType(elementType)) {
1972    // The element count here is the total number of non-VLA elements.
1973    llvm::Value *numElements = CGF.getVLASize(vla).first;
1974
1975    // Effectively, the multiply by the VLA size is part of the GEP.
1976    // GEP indexes are signed, and scaling an index isn't permitted to
1977    // signed-overflow, so we use the same semantics for our explicit
1978    // multiply.  We suppress this if overflow is not undefined behavior.
1979    if (CGF.getLangOpts().isSignedOverflowDefined()) {
1980      index = CGF.Builder.CreateMul(index, numElements, "vla.index");
1981      pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1982    } else {
1983      index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
1984      pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
1985    }
1986    return pointer;
1987  }
1988
1989  // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1990  // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1991  // future proof.
1992  if (elementType->isVoidType() || elementType->isFunctionType()) {
1993    Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1994    result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1995    return CGF.Builder.CreateBitCast(result, pointer->getType());
1996  }
1997
1998  if (CGF.getLangOpts().isSignedOverflowDefined())
1999    return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2000
2001  return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
2002}
2003
2004Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
2005  if (op.LHS->getType()->isPointerTy() ||
2006      op.RHS->getType()->isPointerTy())
2007    return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
2008
2009  if (op.Ty->isSignedIntegerOrEnumerationType()) {
2010    switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
2011    case LangOptions::SOB_Undefined:
2012      return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2013    case LangOptions::SOB_Defined:
2014      return Builder.CreateAdd(op.LHS, op.RHS, "add");
2015    case LangOptions::SOB_Trapping:
2016      return EmitOverflowCheckedBinOp(op);
2017    }
2018  }
2019
2020  if (op.LHS->getType()->isFPOrFPVectorTy())
2021    return Builder.CreateFAdd(op.LHS, op.RHS, "add");
2022
2023  return Builder.CreateAdd(op.LHS, op.RHS, "add");
2024}
2025
2026Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2027  // The LHS is always a pointer if either side is.
2028  if (!op.LHS->getType()->isPointerTy()) {
2029    if (op.Ty->isSignedIntegerOrEnumerationType()) {
2030      switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
2031      case LangOptions::SOB_Undefined:
2032        return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2033      case LangOptions::SOB_Defined:
2034        return Builder.CreateSub(op.LHS, op.RHS, "sub");
2035      case LangOptions::SOB_Trapping:
2036        return EmitOverflowCheckedBinOp(op);
2037      }
2038    }
2039
2040    if (op.LHS->getType()->isFPOrFPVectorTy())
2041      return Builder.CreateFSub(op.LHS, op.RHS, "sub");
2042
2043    return Builder.CreateSub(op.LHS, op.RHS, "sub");
2044  }
2045
2046  // If the RHS is not a pointer, then we have normal pointer
2047  // arithmetic.
2048  if (!op.RHS->getType()->isPointerTy())
2049    return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
2050
2051  // Otherwise, this is a pointer subtraction.
2052
2053  // Do the raw subtraction part.
2054  llvm::Value *LHS
2055    = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2056  llvm::Value *RHS
2057    = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2058  Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
2059
2060  // Okay, figure out the element size.
2061  const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2062  QualType elementType = expr->getLHS()->getType()->getPointeeType();
2063
2064  llvm::Value *divisor = 0;
2065
2066  // For a variable-length array, this is going to be non-constant.
2067  if (const VariableArrayType *vla
2068        = CGF.getContext().getAsVariableArrayType(elementType)) {
2069    llvm::Value *numElements;
2070    llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
2071
2072    divisor = numElements;
2073
2074    // Scale the number of non-VLA elements by the non-VLA element size.
2075    CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2076    if (!eltSize.isOne())
2077      divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2078
2079  // For everything elese, we can just compute it, safe in the
2080  // assumption that Sema won't let anything through that we can't
2081  // safely compute the size of.
2082  } else {
2083    CharUnits elementSize;
2084    // Handle GCC extension for pointer arithmetic on void* and
2085    // function pointer types.
2086    if (elementType->isVoidType() || elementType->isFunctionType())
2087      elementSize = CharUnits::One();
2088    else
2089      elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2090
2091    // Don't even emit the divide for element size of 1.
2092    if (elementSize.isOne())
2093      return diffInChars;
2094
2095    divisor = CGF.CGM.getSize(elementSize);
2096  }
2097
2098  // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2099  // pointer difference in C is only defined in the case where both operands
2100  // are pointing to elements of an array.
2101  return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
2102}
2103
2104Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2105  // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2106  // RHS to the same size as the LHS.
2107  Value *RHS = Ops.RHS;
2108  if (Ops.LHS->getType() != RHS->getType())
2109    RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2110
2111  if (CGF.CatchUndefined
2112      && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2113    unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2114    llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2115    CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2116                                 llvm::ConstantInt::get(RHS->getType(), Width)),
2117                             Cont, CGF.getTrapBB());
2118    CGF.EmitBlock(Cont);
2119  }
2120
2121  return Builder.CreateShl(Ops.LHS, RHS, "shl");
2122}
2123
2124Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2125  // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2126  // RHS to the same size as the LHS.
2127  Value *RHS = Ops.RHS;
2128  if (Ops.LHS->getType() != RHS->getType())
2129    RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2130
2131  if (CGF.CatchUndefined
2132      && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2133    unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2134    llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2135    CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2136                                 llvm::ConstantInt::get(RHS->getType(), Width)),
2137                             Cont, CGF.getTrapBB());
2138    CGF.EmitBlock(Cont);
2139  }
2140
2141  if (Ops.Ty->hasUnsignedIntegerRepresentation())
2142    return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2143  return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2144}
2145
2146enum IntrinsicType { VCMPEQ, VCMPGT };
2147// return corresponding comparison intrinsic for given vector type
2148static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2149                                        BuiltinType::Kind ElemKind) {
2150  switch (ElemKind) {
2151  default: llvm_unreachable("unexpected element type");
2152  case BuiltinType::Char_U:
2153  case BuiltinType::UChar:
2154    return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2155                            llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
2156  case BuiltinType::Char_S:
2157  case BuiltinType::SChar:
2158    return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2159                            llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
2160  case BuiltinType::UShort:
2161    return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2162                            llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
2163  case BuiltinType::Short:
2164    return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2165                            llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
2166  case BuiltinType::UInt:
2167  case BuiltinType::ULong:
2168    return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2169                            llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
2170  case BuiltinType::Int:
2171  case BuiltinType::Long:
2172    return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2173                            llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
2174  case BuiltinType::Float:
2175    return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2176                            llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
2177  }
2178}
2179
2180Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2181                                      unsigned SICmpOpc, unsigned FCmpOpc) {
2182  TestAndClearIgnoreResultAssign();
2183  Value *Result;
2184  QualType LHSTy = E->getLHS()->getType();
2185  if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
2186    assert(E->getOpcode() == BO_EQ ||
2187           E->getOpcode() == BO_NE);
2188    Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2189    Value *RHS = CGF.EmitScalarExpr(E->getRHS());
2190    Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
2191                   CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
2192  } else if (!LHSTy->isAnyComplexType()) {
2193    Value *LHS = Visit(E->getLHS());
2194    Value *RHS = Visit(E->getRHS());
2195
2196    // If AltiVec, the comparison results in a numeric type, so we use
2197    // intrinsics comparing vectors and giving 0 or 1 as a result
2198    if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
2199      // constants for mapping CR6 register bits to predicate result
2200      enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2201
2202      llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2203
2204      // in several cases vector arguments order will be reversed
2205      Value *FirstVecArg = LHS,
2206            *SecondVecArg = RHS;
2207
2208      QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
2209      const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
2210      BuiltinType::Kind ElementKind = BTy->getKind();
2211
2212      switch(E->getOpcode()) {
2213      default: llvm_unreachable("is not a comparison operation");
2214      case BO_EQ:
2215        CR6 = CR6_LT;
2216        ID = GetIntrinsic(VCMPEQ, ElementKind);
2217        break;
2218      case BO_NE:
2219        CR6 = CR6_EQ;
2220        ID = GetIntrinsic(VCMPEQ, ElementKind);
2221        break;
2222      case BO_LT:
2223        CR6 = CR6_LT;
2224        ID = GetIntrinsic(VCMPGT, ElementKind);
2225        std::swap(FirstVecArg, SecondVecArg);
2226        break;
2227      case BO_GT:
2228        CR6 = CR6_LT;
2229        ID = GetIntrinsic(VCMPGT, ElementKind);
2230        break;
2231      case BO_LE:
2232        if (ElementKind == BuiltinType::Float) {
2233          CR6 = CR6_LT;
2234          ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2235          std::swap(FirstVecArg, SecondVecArg);
2236        }
2237        else {
2238          CR6 = CR6_EQ;
2239          ID = GetIntrinsic(VCMPGT, ElementKind);
2240        }
2241        break;
2242      case BO_GE:
2243        if (ElementKind == BuiltinType::Float) {
2244          CR6 = CR6_LT;
2245          ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2246        }
2247        else {
2248          CR6 = CR6_EQ;
2249          ID = GetIntrinsic(VCMPGT, ElementKind);
2250          std::swap(FirstVecArg, SecondVecArg);
2251        }
2252        break;
2253      }
2254
2255      Value *CR6Param = Builder.getInt32(CR6);
2256      llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2257      Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2258      return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2259    }
2260
2261    if (LHS->getType()->isFPOrFPVectorTy()) {
2262      Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
2263                                  LHS, RHS, "cmp");
2264    } else if (LHSTy->hasSignedIntegerRepresentation()) {
2265      Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
2266                                  LHS, RHS, "cmp");
2267    } else {
2268      // Unsigned integers and pointers.
2269      Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2270                                  LHS, RHS, "cmp");
2271    }
2272
2273    // If this is a vector comparison, sign extend the result to the appropriate
2274    // vector integer type and return it (don't convert to bool).
2275    if (LHSTy->isVectorType())
2276      return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2277
2278  } else {
2279    // Complex Comparison: can only be an equality comparison.
2280    CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2281    CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
2282
2283    QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
2284
2285    Value *ResultR, *ResultI;
2286    if (CETy->isRealFloatingType()) {
2287      ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2288                                   LHS.first, RHS.first, "cmp.r");
2289      ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2290                                   LHS.second, RHS.second, "cmp.i");
2291    } else {
2292      // Complex comparisons can only be equality comparisons.  As such, signed
2293      // and unsigned opcodes are the same.
2294      ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2295                                   LHS.first, RHS.first, "cmp.r");
2296      ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2297                                   LHS.second, RHS.second, "cmp.i");
2298    }
2299
2300    if (E->getOpcode() == BO_EQ) {
2301      Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2302    } else {
2303      assert(E->getOpcode() == BO_NE &&
2304             "Complex comparison other than == or != ?");
2305      Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2306    }
2307  }
2308
2309  return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2310}
2311
2312Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
2313  bool Ignore = TestAndClearIgnoreResultAssign();
2314
2315  Value *RHS;
2316  LValue LHS;
2317
2318  switch (E->getLHS()->getType().getObjCLifetime()) {
2319  case Qualifiers::OCL_Strong:
2320    llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2321    break;
2322
2323  case Qualifiers::OCL_Autoreleasing:
2324    llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
2325    break;
2326
2327  case Qualifiers::OCL_Weak:
2328    RHS = Visit(E->getRHS());
2329    LHS = EmitCheckedLValue(E->getLHS());
2330    RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2331    break;
2332
2333  // No reason to do any of these differently.
2334  case Qualifiers::OCL_None:
2335  case Qualifiers::OCL_ExplicitNone:
2336    // __block variables need to have the rhs evaluated first, plus
2337    // this should improve codegen just a little.
2338    RHS = Visit(E->getRHS());
2339    LHS = EmitCheckedLValue(E->getLHS());
2340
2341    // Store the value into the LHS.  Bit-fields are handled specially
2342    // because the result is altered by the store, i.e., [C99 6.5.16p1]
2343    // 'An assignment expression has the value of the left operand after
2344    // the assignment...'.
2345    if (LHS.isBitField())
2346      CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
2347    else
2348      CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
2349  }
2350
2351  // If the result is clearly ignored, return now.
2352  if (Ignore)
2353    return 0;
2354
2355  // The result of an assignment in C is the assigned r-value.
2356  if (!CGF.getContext().getLangOpts().CPlusPlus)
2357    return RHS;
2358
2359  // If the lvalue is non-volatile, return the computed value of the assignment.
2360  if (!LHS.isVolatileQualified())
2361    return RHS;
2362
2363  // Otherwise, reload the value.
2364  return EmitLoadOfLValue(LHS);
2365}
2366
2367Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
2368
2369  // Perform vector logical and on comparisons with zero vectors.
2370  if (E->getType()->isVectorType()) {
2371    Value *LHS = Visit(E->getLHS());
2372    Value *RHS = Visit(E->getRHS());
2373    Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2374    LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2375    RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2376    Value *And = Builder.CreateAnd(LHS, RHS);
2377    return Builder.CreateSExt(And, Zero->getType(), "sext");
2378  }
2379
2380  llvm::Type *ResTy = ConvertType(E->getType());
2381
2382  // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2383  // If we have 1 && X, just emit X without inserting the control flow.
2384  bool LHSCondVal;
2385  if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2386    if (LHSCondVal) { // If we have 1 && X, just emit X.
2387      Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2388      // ZExt result to int or bool.
2389      return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
2390    }
2391
2392    // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
2393    if (!CGF.ContainsLabel(E->getRHS()))
2394      return llvm::Constant::getNullValue(ResTy);
2395  }
2396
2397  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2398  llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
2399
2400  CodeGenFunction::ConditionalEvaluation eval(CGF);
2401
2402  // Branch on the LHS first.  If it is false, go to the failure (cont) block.
2403  CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2404
2405  // Any edges into the ContBlock are now from an (indeterminate number of)
2406  // edges from this first condition.  All of these values will be false.  Start
2407  // setting up the PHI node in the Cont Block for this.
2408  llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
2409                                            "", ContBlock);
2410  for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2411       PI != PE; ++PI)
2412    PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
2413
2414  eval.begin(CGF);
2415  CGF.EmitBlock(RHSBlock);
2416  Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2417  eval.end(CGF);
2418
2419  // Reaquire the RHS block, as there may be subblocks inserted.
2420  RHSBlock = Builder.GetInsertBlock();
2421
2422  // Emit an unconditional branch from this block to ContBlock.  Insert an entry
2423  // into the phi node for the edge with the value of RHSCond.
2424  if (CGF.getDebugInfo())
2425    // There is no need to emit line number for unconditional branch.
2426    Builder.SetCurrentDebugLocation(llvm::DebugLoc());
2427  CGF.EmitBlock(ContBlock);
2428  PN->addIncoming(RHSCond, RHSBlock);
2429
2430  // ZExt result to int.
2431  return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
2432}
2433
2434Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
2435
2436  // Perform vector logical or on comparisons with zero vectors.
2437  if (E->getType()->isVectorType()) {
2438    Value *LHS = Visit(E->getLHS());
2439    Value *RHS = Visit(E->getRHS());
2440    Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2441    LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2442    RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2443    Value *Or = Builder.CreateOr(LHS, RHS);
2444    return Builder.CreateSExt(Or, Zero->getType(), "sext");
2445  }
2446
2447  llvm::Type *ResTy = ConvertType(E->getType());
2448
2449  // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2450  // If we have 0 || X, just emit X without inserting the control flow.
2451  bool LHSCondVal;
2452  if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2453    if (!LHSCondVal) { // If we have 0 || X, just emit X.
2454      Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2455      // ZExt result to int or bool.
2456      return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
2457    }
2458
2459    // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
2460    if (!CGF.ContainsLabel(E->getRHS()))
2461      return llvm::ConstantInt::get(ResTy, 1);
2462  }
2463
2464  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2465  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
2466
2467  CodeGenFunction::ConditionalEvaluation eval(CGF);
2468
2469  // Branch on the LHS first.  If it is true, go to the success (cont) block.
2470  CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2471
2472  // Any edges into the ContBlock are now from an (indeterminate number of)
2473  // edges from this first condition.  All of these values will be true.  Start
2474  // setting up the PHI node in the Cont Block for this.
2475  llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
2476                                            "", ContBlock);
2477  for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2478       PI != PE; ++PI)
2479    PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
2480
2481  eval.begin(CGF);
2482
2483  // Emit the RHS condition as a bool value.
2484  CGF.EmitBlock(RHSBlock);
2485  Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2486
2487  eval.end(CGF);
2488
2489  // Reaquire the RHS block, as there may be subblocks inserted.
2490  RHSBlock = Builder.GetInsertBlock();
2491
2492  // Emit an unconditional branch from this block to ContBlock.  Insert an entry
2493  // into the phi node for the edge with the value of RHSCond.
2494  CGF.EmitBlock(ContBlock);
2495  PN->addIncoming(RHSCond, RHSBlock);
2496
2497  // ZExt result to int.
2498  return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
2499}
2500
2501Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
2502  CGF.EmitIgnoredExpr(E->getLHS());
2503  CGF.EnsureInsertPoint();
2504  return Visit(E->getRHS());
2505}
2506
2507//===----------------------------------------------------------------------===//
2508//                             Other Operators
2509//===----------------------------------------------------------------------===//
2510
2511/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2512/// expression is cheap enough and side-effect-free enough to evaluate
2513/// unconditionally instead of conditionally.  This is used to convert control
2514/// flow into selects in some cases.
2515static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2516                                                   CodeGenFunction &CGF) {
2517  E = E->IgnoreParens();
2518
2519  // Anything that is an integer or floating point constant is fine.
2520  if (E->isConstantInitializer(CGF.getContext(), false))
2521    return true;
2522
2523  // Non-volatile automatic variables too, to get "cond ? X : Y" where
2524  // X and Y are local variables.
2525  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2526    if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2527      if (VD->hasLocalStorage() && !(CGF.getContext()
2528                                     .getCanonicalType(VD->getType())
2529                                     .isVolatileQualified()))
2530        return true;
2531
2532  return false;
2533}
2534
2535
2536Value *ScalarExprEmitter::
2537VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
2538  TestAndClearIgnoreResultAssign();
2539
2540  // Bind the common expression if necessary.
2541  CodeGenFunction::OpaqueValueMapping binding(CGF, E);
2542
2543  Expr *condExpr = E->getCond();
2544  Expr *lhsExpr = E->getTrueExpr();
2545  Expr *rhsExpr = E->getFalseExpr();
2546
2547  // If the condition constant folds and can be elided, try to avoid emitting
2548  // the condition and the dead arm.
2549  bool CondExprBool;
2550  if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
2551    Expr *live = lhsExpr, *dead = rhsExpr;
2552    if (!CondExprBool) std::swap(live, dead);
2553
2554    // If the dead side doesn't have labels we need, just emit the Live part.
2555    if (!CGF.ContainsLabel(dead)) {
2556      Value *Result = Visit(live);
2557
2558      // If the live part is a throw expression, it acts like it has a void
2559      // type, so evaluating it returns a null Value*.  However, a conditional
2560      // with non-void type must return a non-null Value*.
2561      if (!Result && !E->getType()->isVoidType())
2562        Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
2563
2564      return Result;
2565    }
2566  }
2567
2568  // OpenCL: If the condition is a vector, we can treat this condition like
2569  // the select function.
2570  if (CGF.getContext().getLangOpts().OpenCL
2571      && condExpr->getType()->isVectorType()) {
2572    llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
2573    llvm::Value *LHS = Visit(lhsExpr);
2574    llvm::Value *RHS = Visit(rhsExpr);
2575
2576    llvm::Type *condType = ConvertType(condExpr->getType());
2577    llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
2578
2579    unsigned numElem = vecTy->getNumElements();
2580    llvm::Type *elemType = vecTy->getElementType();
2581
2582    llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
2583    llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2584    llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2585                                          llvm::VectorType::get(elemType,
2586                                                                numElem),
2587                                          "sext");
2588    llvm::Value *tmp2 = Builder.CreateNot(tmp);
2589
2590    // Cast float to int to perform ANDs if necessary.
2591    llvm::Value *RHSTmp = RHS;
2592    llvm::Value *LHSTmp = LHS;
2593    bool wasCast = false;
2594    llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
2595    if (rhsVTy->getElementType()->isFloatTy()) {
2596      RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2597      LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2598      wasCast = true;
2599    }
2600
2601    llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2602    llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2603    llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2604    if (wasCast)
2605      tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2606
2607    return tmp5;
2608  }
2609
2610  // If this is a really simple expression (like x ? 4 : 5), emit this as a
2611  // select instead of as control flow.  We can only do this if it is cheap and
2612  // safe to evaluate the LHS and RHS unconditionally.
2613  if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
2614      isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
2615    llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
2616    llvm::Value *LHS = Visit(lhsExpr);
2617    llvm::Value *RHS = Visit(rhsExpr);
2618    if (!LHS) {
2619      // If the conditional has void type, make sure we return a null Value*.
2620      assert(!RHS && "LHS and RHS types must match");
2621      return 0;
2622    }
2623    return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2624  }
2625
2626  llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2627  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
2628  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
2629
2630  CodeGenFunction::ConditionalEvaluation eval(CGF);
2631  CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
2632
2633  CGF.EmitBlock(LHSBlock);
2634  eval.begin(CGF);
2635  Value *LHS = Visit(lhsExpr);
2636  eval.end(CGF);
2637
2638  LHSBlock = Builder.GetInsertBlock();
2639  Builder.CreateBr(ContBlock);
2640
2641  CGF.EmitBlock(RHSBlock);
2642  eval.begin(CGF);
2643  Value *RHS = Visit(rhsExpr);
2644  eval.end(CGF);
2645
2646  RHSBlock = Builder.GetInsertBlock();
2647  CGF.EmitBlock(ContBlock);
2648
2649  // If the LHS or RHS is a throw expression, it will be legitimately null.
2650  if (!LHS)
2651    return RHS;
2652  if (!RHS)
2653    return LHS;
2654
2655  // Create a PHI node for the real part.
2656  llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
2657  PN->addIncoming(LHS, LHSBlock);
2658  PN->addIncoming(RHS, RHSBlock);
2659  return PN;
2660}
2661
2662Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
2663  return Visit(E->getChosenSubExpr(CGF.getContext()));
2664}
2665
2666Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
2667  llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
2668  llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2669
2670  // If EmitVAArg fails, we fall back to the LLVM instruction.
2671  if (!ArgPtr)
2672    return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2673
2674  // FIXME Volatility.
2675  return Builder.CreateLoad(ArgPtr);
2676}
2677
2678Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2679  return CGF.EmitBlockLiteral(block);
2680}
2681
2682Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
2683  Value *Src  = CGF.EmitScalarExpr(E->getSrcExpr());
2684  llvm::Type *DstTy = ConvertType(E->getType());
2685
2686  // Going from vec4->vec3 or vec3->vec4 is a special case and requires
2687  // a shuffle vector instead of a bitcast.
2688  llvm::Type *SrcTy = Src->getType();
2689  if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
2690    unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
2691    unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
2692    if ((numElementsDst == 3 && numElementsSrc == 4)
2693        || (numElementsDst == 4 && numElementsSrc == 3)) {
2694
2695
2696      // In the case of going from int4->float3, a bitcast is needed before
2697      // doing a shuffle.
2698      llvm::Type *srcElemTy =
2699      cast<llvm::VectorType>(SrcTy)->getElementType();
2700      llvm::Type *dstElemTy =
2701      cast<llvm::VectorType>(DstTy)->getElementType();
2702
2703      if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
2704          || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
2705        // Create a float type of the same size as the source or destination.
2706        llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
2707                                                                 numElementsSrc);
2708
2709        Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
2710      }
2711
2712      llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
2713
2714      SmallVector<llvm::Constant*, 3> Args;
2715      Args.push_back(Builder.getInt32(0));
2716      Args.push_back(Builder.getInt32(1));
2717      Args.push_back(Builder.getInt32(2));
2718
2719      if (numElementsDst == 4)
2720        Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
2721
2722      llvm::Constant *Mask = llvm::ConstantVector::get(Args);
2723
2724      return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
2725    }
2726  }
2727
2728  return Builder.CreateBitCast(Src, DstTy, "astype");
2729}
2730
2731Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
2732  return CGF.EmitAtomicExpr(E).getScalarVal();
2733}
2734
2735//===----------------------------------------------------------------------===//
2736//                         Entry Point into this File
2737//===----------------------------------------------------------------------===//
2738
2739/// EmitScalarExpr - Emit the computation of the specified expression of scalar
2740/// type, ignoring the result.
2741Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
2742  assert(E && !hasAggregateLLVMType(E->getType()) &&
2743         "Invalid scalar expression to emit");
2744
2745  if (isa<CXXDefaultArgExpr>(E))
2746    disableDebugInfo();
2747  Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
2748    .Visit(const_cast<Expr*>(E));
2749  if (isa<CXXDefaultArgExpr>(E))
2750    enableDebugInfo();
2751  return V;
2752}
2753
2754/// EmitScalarConversion - Emit a conversion from the specified type to the
2755/// specified destination type, both of which are LLVM scalar types.
2756Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2757                                             QualType DstTy) {
2758  assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2759         "Invalid scalar expression to emit");
2760  return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2761}
2762
2763/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2764/// type to the specified destination type, where the destination type is an
2765/// LLVM scalar type.
2766Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2767                                                      QualType SrcTy,
2768                                                      QualType DstTy) {
2769  assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
2770         "Invalid complex -> scalar conversion");
2771  return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2772                                                                DstTy);
2773}
2774
2775
2776llvm::Value *CodeGenFunction::
2777EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2778                        bool isInc, bool isPre) {
2779  return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2780}
2781
2782LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2783  llvm::Value *V;
2784  // object->isa or (*object).isa
2785  // Generate code as for: *(Class*)object
2786  // build Class* type
2787  llvm::Type *ClassPtrTy = ConvertType(E->getType());
2788
2789  Expr *BaseExpr = E->getBase();
2790  if (BaseExpr->isRValue()) {
2791    V = CreateMemTemp(E->getType(), "resval");
2792    llvm::Value *Src = EmitScalarExpr(BaseExpr);
2793    Builder.CreateStore(Src, V);
2794    V = ScalarExprEmitter(*this).EmitLoadOfLValue(
2795      MakeNaturalAlignAddrLValue(V, E->getType()));
2796  } else {
2797    if (E->isArrow())
2798      V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2799    else
2800      V = EmitLValue(BaseExpr).getAddress();
2801  }
2802
2803  // build Class* type
2804  ClassPtrTy = ClassPtrTy->getPointerTo();
2805  V = Builder.CreateBitCast(V, ClassPtrTy);
2806  return MakeNaturalAlignAddrLValue(V, E->getType());
2807}
2808
2809
2810LValue CodeGenFunction::EmitCompoundAssignmentLValue(
2811                                            const CompoundAssignOperator *E) {
2812  ScalarExprEmitter Scalar(*this);
2813  Value *Result = 0;
2814  switch (E->getOpcode()) {
2815#define COMPOUND_OP(Op)                                                       \
2816    case BO_##Op##Assign:                                                     \
2817      return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
2818                                             Result)
2819  COMPOUND_OP(Mul);
2820  COMPOUND_OP(Div);
2821  COMPOUND_OP(Rem);
2822  COMPOUND_OP(Add);
2823  COMPOUND_OP(Sub);
2824  COMPOUND_OP(Shl);
2825  COMPOUND_OP(Shr);
2826  COMPOUND_OP(And);
2827  COMPOUND_OP(Xor);
2828  COMPOUND_OP(Or);
2829#undef COMPOUND_OP
2830
2831  case BO_PtrMemD:
2832  case BO_PtrMemI:
2833  case BO_Mul:
2834  case BO_Div:
2835  case BO_Rem:
2836  case BO_Add:
2837  case BO_Sub:
2838  case BO_Shl:
2839  case BO_Shr:
2840  case BO_LT:
2841  case BO_GT:
2842  case BO_LE:
2843  case BO_GE:
2844  case BO_EQ:
2845  case BO_NE:
2846  case BO_And:
2847  case BO_Xor:
2848  case BO_Or:
2849  case BO_LAnd:
2850  case BO_LOr:
2851  case BO_Assign:
2852  case BO_Comma:
2853    llvm_unreachable("Not valid compound assignment operators");
2854  }
2855
2856  llvm_unreachable("Unhandled compound assignment operator");
2857}
2858