blob: 85a0de2b919e285efec0c5a1d2aa41c3fdfa315e [file] [log] [blame]
Chris Lattner2da04b32007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner2da04b32007-08-24 05:35:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
John McCall5d865c322010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CGDebugInfo.h"
Fariborz Jahanian07ca7272009-10-10 20:07:56 +000017#include "CGObjCRuntime.h"
Chris Lattner2da04b32007-08-24 05:35:26 +000018#include "CodeGenModule.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar6630e102008-08-12 05:08:18 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000021#include "clang/AST/RecordLayout.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000022#include "clang/AST/StmtVisitor.h"
Chris Lattnerff2367c2008-04-20 00:50:39 +000023#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth735e6d82014-03-04 11:46:22 +000025#include "llvm/IR/CFG.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/GlobalVariable.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/Module.h"
Chris Lattner1800c182008-01-03 07:05:49 +000032#include <cstdarg>
Ted Kremenekf182e812007-12-10 23:44:32 +000033
Chris Lattner2da04b32007-08-24 05:35:26 +000034using namespace clang;
35using namespace CodeGen;
36using llvm::Value;
37
38//===----------------------------------------------------------------------===//
39// Scalar Expression Emitter
40//===----------------------------------------------------------------------===//
41
Benjamin Kramerfb5e5842010-10-22 16:48:22 +000042namespace {
Chris Lattner2da04b32007-08-24 05:35:26 +000043struct BinOpInfo {
44 Value *LHS;
45 Value *RHS;
Chris Lattner3d966d62007-08-24 21:00:35 +000046 QualType Ty; // Computation Type.
Chris Lattner0bf27622010-06-26 21:48:21 +000047 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
Lang Hames5de91cc2012-10-02 04:45:10 +000048 bool FPContractable;
Chris Lattner0bf27622010-06-26 21:48:21 +000049 const Expr *E; // Entire expr, for error unsupported. May not be binop.
Chris Lattner2da04b32007-08-24 05:35:26 +000050};
51
John McCalle84af4e2010-11-13 01:35:44 +000052static bool MustVisitNullValue(const Expr *E) {
53 // If a null pointer expression's type is the C++0x nullptr_t, then
54 // it's not necessarily a simple constant and it must be evaluated
55 // for its potential side effects.
56 return E->getType()->isNullPtrType();
57}
58
Benjamin Kramer337e3a52009-11-28 19:45:26 +000059class ScalarExprEmitter
Chris Lattner2da04b32007-08-24 05:35:26 +000060 : public StmtVisitor<ScalarExprEmitter, Value*> {
61 CodeGenFunction &CGF;
Daniel Dunbarcb463852008-11-01 01:53:16 +000062 CGBuilderTy &Builder;
Mike Stumpdf0fe272009-05-29 15:46:01 +000063 bool IgnoreResultAssign;
Owen Anderson170229f2009-07-14 23:10:40 +000064 llvm::LLVMContext &VMContext;
Chris Lattner2da04b32007-08-24 05:35:26 +000065public:
66
Mike Stumpdf0fe272009-05-29 15:46:01 +000067 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stump4a3999f2009-09-09 13:00:44 +000068 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Anderson170229f2009-07-14 23:10:40 +000069 VMContext(cgf.getLLVMContext()) {
Chris Lattner2da04b32007-08-24 05:35:26 +000070 }
Mike Stump4a3999f2009-09-09 13:00:44 +000071
Chris Lattner2da04b32007-08-24 05:35:26 +000072 //===--------------------------------------------------------------------===//
73 // Utilities
74 //===--------------------------------------------------------------------===//
75
Mike Stumpdf0fe272009-05-29 15:46:01 +000076 bool TestAndClearIgnoreResultAssign() {
Chris Lattner2a7deb62009-07-08 01:08:03 +000077 bool I = IgnoreResultAssign;
78 IgnoreResultAssign = false;
79 return I;
80 }
Mike Stumpdf0fe272009-05-29 15:46:01 +000081
Chris Lattner2192fe52011-07-18 04:24:23 +000082 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
Chris Lattner2da04b32007-08-24 05:35:26 +000083 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
Richard Smith4d1458e2012-09-08 02:08:36 +000084 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
85 return CGF.EmitCheckedLValue(E, TCK);
Richard Smith69d0d262012-08-24 00:54:33 +000086 }
Chris Lattner2da04b32007-08-24 05:35:26 +000087
Alexey Samsonove396bfc2014-11-11 22:03:54 +000088 void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerKind>> Checks,
89 const BinOpInfo &Info);
Richard Smithe30752c2012-10-09 19:52:38 +000090
Nick Lewycky2d84e842013-10-02 02:29:49 +000091 Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
92 return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
Chris Lattner2da04b32007-08-24 05:35:26 +000093 }
Mike Stump4a3999f2009-09-09 13:00:44 +000094
Hal Finkel64567a82014-10-04 15:26:49 +000095 void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
96 const AlignValueAttr *AVAttr = nullptr;
97 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
98 const ValueDecl *VD = DRE->getDecl();
99
100 if (VD->getType()->isReferenceType()) {
101 if (const auto *TTy =
102 dyn_cast<TypedefType>(VD->getType().getNonReferenceType()))
103 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
104 } else {
105 // Assumptions for function parameters are emitted at the start of the
106 // function, so there is no need to repeat that here.
107 if (isa<ParmVarDecl>(VD))
108 return;
109
110 AVAttr = VD->getAttr<AlignValueAttr>();
111 }
112 }
113
114 if (!AVAttr)
115 if (const auto *TTy =
116 dyn_cast<TypedefType>(E->getType()))
117 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
118
119 if (!AVAttr)
120 return;
121
122 Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
123 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
124 CGF.EmitAlignmentAssumption(V, AlignmentCI->getZExtValue());
125 }
126
Chris Lattner2da04b32007-08-24 05:35:26 +0000127 /// EmitLoadOfLValue - Given an expression with complex type that represents a
128 /// value l-value, this method emits the address of the l-value, then loads
129 /// and returns the result.
130 Value *EmitLoadOfLValue(const Expr *E) {
Hal Finkel64567a82014-10-04 15:26:49 +0000131 Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
132 E->getExprLoc());
133
134 EmitLValueAlignmentAssumption(E, V);
135 return V;
Chris Lattner2da04b32007-08-24 05:35:26 +0000136 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000137
Chris Lattnere0044382007-08-26 16:42:57 +0000138 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner2e928882007-08-26 17:25:57 +0000139 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnere0044382007-08-26 16:42:57 +0000140 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stump4a3999f2009-09-09 13:00:44 +0000141
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000142 /// \brief Emit a check that a conversion to or from a floating-point type
143 /// does not overflow.
144 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
145 Value *Src, QualType SrcType,
146 QualType DstType, llvm::Type *DstTy);
147
Chris Lattner3474c202007-08-26 06:48:56 +0000148 /// EmitScalarConversion - Emit a conversion from the specified type to the
149 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner42e6b812007-08-26 16:34:22 +0000150 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
151
152 /// EmitComplexToScalarConversion - Emit a conversion from the specified
Mike Stump4a3999f2009-09-09 13:00:44 +0000153 /// complex type to the specified destination type, where the destination type
154 /// is an LLVM scalar type.
Chris Lattner42e6b812007-08-26 16:34:22 +0000155 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
156 QualType SrcTy, QualType DstTy);
Mike Stumpab3afd82009-02-12 18:29:15 +0000157
Anders Carlsson5b944432010-05-22 17:45:10 +0000158 /// EmitNullValue - Emit a value that corresponds to null for the given type.
159 Value *EmitNullValue(QualType Ty);
160
John McCall8cb679e2010-11-15 09:13:47 +0000161 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
162 Value *EmitFloatToBoolConversion(Value *V) {
163 // Compare against 0.0 for fp scalars.
164 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
165 return Builder.CreateFCmpUNE(V, Zero, "tobool");
166 }
167
168 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
169 Value *EmitPointerToBoolConversion(Value *V) {
170 Value *Zero = llvm::ConstantPointerNull::get(
171 cast<llvm::PointerType>(V->getType()));
172 return Builder.CreateICmpNE(V, Zero, "tobool");
173 }
174
175 Value *EmitIntToBoolConversion(Value *V) {
176 // Because of the type rules of C, we often end up computing a
177 // logical value, then zero extending it to int, then wanting it
178 // as a logical value again. Optimize this common case.
179 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
180 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
181 Value *Result = ZI->getOperand(0);
182 // If there aren't any more uses, zap the instruction to save space.
183 // Note that there can be more uses, for example if this
184 // is the result of an assignment.
185 if (ZI->use_empty())
186 ZI->eraseFromParent();
187 return Result;
188 }
189 }
190
Chris Lattner2531eb42011-04-19 22:55:03 +0000191 return Builder.CreateIsNotNull(V, "tobool");
John McCall8cb679e2010-11-15 09:13:47 +0000192 }
193
Chris Lattner2da04b32007-08-24 05:35:26 +0000194 //===--------------------------------------------------------------------===//
195 // Visitor Methods
196 //===--------------------------------------------------------------------===//
197
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000198 Value *Visit(Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +0000199 ApplyDebugLocation DL(CGF, E);
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000200 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
201 }
Craig Toppera97d7e72013-07-26 06:16:11 +0000202
Chris Lattner2da04b32007-08-24 05:35:26 +0000203 Value *VisitStmt(Stmt *S) {
Ted Kremenekd4e5fba2007-12-11 21:27:55 +0000204 S->dump(CGF.getContext().getSourceManager());
David Blaikie83d382b2011-09-23 05:06:16 +0000205 llvm_unreachable("Stmt can't have complex result type!");
Chris Lattner2da04b32007-08-24 05:35:26 +0000206 }
207 Value *VisitExpr(Expr *S);
Craig Toppera97d7e72013-07-26 06:16:11 +0000208
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000209 Value *VisitParenExpr(ParenExpr *PE) {
Craig Toppera97d7e72013-07-26 06:16:11 +0000210 return Visit(PE->getSubExpr());
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000211 }
John McCall7c454bb2011-07-15 05:09:51 +0000212 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
Craig Toppera97d7e72013-07-26 06:16:11 +0000213 return Visit(E->getReplacement());
John McCall7c454bb2011-07-15 05:09:51 +0000214 }
Peter Collingbourne91147592011-04-15 00:35:48 +0000215 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
216 return Visit(GE->getResultExpr());
217 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000218
219 // Leaves.
220 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000221 return Builder.getInt(E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000222 }
223 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersone05f2ed2009-07-27 21:00:51 +0000224 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000225 }
226 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000227 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000228 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000229 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
230 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
231 }
Nate Begeman4c18c232007-11-15 05:40:03 +0000232 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000233 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begeman4c18c232007-11-15 05:40:03 +0000234 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000235 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlsson5b944432010-05-22 17:45:10 +0000236 return EmitNullValue(E->getType());
Argyrios Kyrtzidisce4528f2008-08-23 19:35:47 +0000237 }
Anders Carlsson39def3a2008-12-21 22:39:40 +0000238 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlsson5b944432010-05-22 17:45:10 +0000239 return EmitNullValue(E->getType());
Anders Carlsson39def3a2008-12-21 22:39:40 +0000240 }
Eli Friedmand7c72322010-08-05 09:58:49 +0000241 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Peter Collingbournee190dee2011-03-11 19:24:49 +0000242 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000243 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattner6c4d2552009-10-28 23:59:40 +0000244 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
245 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000246 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000247
Douglas Gregorbe7b5482011-01-12 22:11:34 +0000248 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000249 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
Douglas Gregorbe7b5482011-01-12 22:11:34 +0000250 }
John McCall1bf58462011-02-16 08:02:54 +0000251
John McCallfe96e0b2011-11-06 09:01:30 +0000252 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
253 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
254 }
255
John McCall1bf58462011-02-16 08:02:54 +0000256 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCallc07a0c72011-02-17 10:25:35 +0000257 if (E->isGLValue())
Nick Lewycky2d84e842013-10-02 02:29:49 +0000258 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E), E->getExprLoc());
John McCall1bf58462011-02-16 08:02:54 +0000259
260 // Otherwise, assume the mapping is the scalar directly.
John McCallc07a0c72011-02-17 10:25:35 +0000261 return CGF.getOpaqueRValueMapping(E).getScalarVal();
John McCall1bf58462011-02-16 08:02:54 +0000262 }
John McCall71335052012-03-10 03:05:10 +0000263
Chris Lattner2da04b32007-08-24 05:35:26 +0000264 // l-values.
John McCall113bee02012-03-10 09:33:50 +0000265 Value *VisitDeclRefExpr(DeclRefExpr *E) {
266 if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
John McCall71335052012-03-10 03:05:10 +0000267 if (result.isReference())
Nick Lewycky2d84e842013-10-02 02:29:49 +0000268 return EmitLoadOfLValue(result.getReferenceLValue(CGF, E),
269 E->getExprLoc());
John McCall71335052012-03-10 03:05:10 +0000270 return result.getValue();
Richard Smithbc6387672012-03-02 23:27:11 +0000271 }
John McCall113bee02012-03-10 09:33:50 +0000272 return EmitLoadOfLValue(E);
John McCall71335052012-03-10 03:05:10 +0000273 }
274
Mike Stump4a3999f2009-09-09 13:00:44 +0000275 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
276 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000277 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000278 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
279 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000280 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000281 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar55310df2008-08-27 06:57:25 +0000282 return EmitLoadOfLValue(E);
283 }
Daniel Dunbar55310df2008-08-27 06:57:25 +0000284 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
Craig Toppera97d7e72013-07-26 06:16:11 +0000285 if (E->getMethodDecl() &&
Alp Toker314cc812014-01-25 16:55:45 +0000286 E->getMethodDecl()->getReturnType()->isReferenceType())
Fariborz Jahanianff989032011-03-02 20:09:49 +0000287 return EmitLoadOfLValue(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000288 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbarc8317a42008-08-23 10:51:21 +0000289 }
290
Fariborz Jahaniana5fee262009-12-09 19:05:56 +0000291 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000292 LValue LV = CGF.EmitObjCIsaExpr(E);
Nick Lewycky2d84e842013-10-02 02:29:49 +0000293 Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
Fariborz Jahaniana5fee262009-12-09 19:05:56 +0000294 return V;
295 }
296
Chris Lattner2da04b32007-08-24 05:35:26 +0000297 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000298 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Hal Finkelc4d7c822013-09-18 03:29:45 +0000299 Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
Eli Friedmancb422f12009-11-26 03:22:21 +0000300 Value *VisitMemberExpr(MemberExpr *E);
Nate Begemance4d7fc2008-04-18 23:10:10 +0000301 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattner084bc322008-10-26 23:53:12 +0000302 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
303 return EmitLoadOfLValue(E);
304 }
Devang Patel43fc86d2007-10-24 17:18:43 +0000305
Nate Begeman19351632009-10-18 20:10:40 +0000306 Value *VisitInitListExpr(InitListExpr *E);
Mike Stump4a3999f2009-09-09 13:00:44 +0000307
Douglas Gregor0202cb42009-01-29 17:44:32 +0000308 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithd82a2ce2012-12-21 03:17:28 +0000309 return EmitNullValue(E->getType());
Douglas Gregor0202cb42009-01-29 17:44:32 +0000310 }
John McCall23c29fe2011-06-24 21:55:10 +0000311 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000312 if (E->getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000313 CGF.EmitVariablyModifiedType(E->getType());
David Blaikie66088d52014-09-24 17:01:27 +0000314
315 if (CGDebugInfo *DI = CGF.getDebugInfo())
316 DI->EmitExplicitCastType(E->getType());
317
John McCall23c29fe2011-06-24 21:55:10 +0000318 return VisitCastExpr(E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000319 }
John McCall23c29fe2011-06-24 21:55:10 +0000320 Value *VisitCastExpr(CastExpr *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000321
322 Value *VisitCallExpr(const CallExpr *E) {
David Majnemerced8bdf2015-02-25 17:36:15 +0000323 if (E->getCallReturnType(CGF.getContext())->isReferenceType())
Anders Carlssond8b7ae22009-05-27 03:37:57 +0000324 return EmitLoadOfLValue(E);
Mike Stump4a3999f2009-09-09 13:00:44 +0000325
Hal Finkel64567a82014-10-04 15:26:49 +0000326 Value *V = CGF.EmitCallExpr(E).getScalarVal();
327
328 EmitLValueAlignmentAssumption(E, V);
329 return V;
Chris Lattner2da04b32007-08-24 05:35:26 +0000330 }
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000331
Chris Lattner04a913b2007-08-31 22:09:40 +0000332 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stumpcb2fbcb2009-02-21 20:00:35 +0000333
Chris Lattner2da04b32007-08-24 05:35:26 +0000334 // Unary Operators.
Chris Lattner2da04b32007-08-24 05:35:26 +0000335 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000336 LValue LV = EmitLValue(E->getSubExpr());
337 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner2da04b32007-08-24 05:35:26 +0000338 }
339 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000340 LValue LV = EmitLValue(E->getSubExpr());
341 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner2da04b32007-08-24 05:35:26 +0000342 }
343 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000344 LValue LV = EmitLValue(E->getSubExpr());
345 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner2da04b32007-08-24 05:35:26 +0000346 }
347 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000348 LValue LV = EmitLValue(E->getSubExpr());
349 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner2da04b32007-08-24 05:35:26 +0000350 }
Chris Lattner05dc78c2010-06-26 22:09:34 +0000351
Anton Yartsev85129b82011-02-07 02:17:30 +0000352 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
353 llvm::Value *InVal,
354 llvm::Value *NextVal,
355 bool IsInc);
356
Chris Lattner05dc78c2010-06-26 22:09:34 +0000357 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
358 bool isInc, bool isPre);
359
Craig Toppera97d7e72013-07-26 06:16:11 +0000360
Chris Lattner2da04b32007-08-24 05:35:26 +0000361 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCallf3a88602011-02-03 08:15:49 +0000362 if (isa<MemberPointerType>(E->getType())) // never sugared
363 return CGF.CGM.getMemberPointerConstant(E);
364
Chris Lattner2da04b32007-08-24 05:35:26 +0000365 return EmitLValue(E->getSubExpr()).getAddress();
366 }
John McCall59482722010-12-04 12:43:24 +0000367 Value *VisitUnaryDeref(const UnaryOperator *E) {
368 if (E->getType()->isVoidType())
369 return Visit(E->getSubExpr()); // the actual value should be unused
370 return EmitLoadOfLValue(E);
371 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000372 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +0000373 // This differs from gcc, though, most likely due to a bug in gcc.
374 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +0000375 return Visit(E->getSubExpr());
376 }
377 Value *VisitUnaryMinus (const UnaryOperator *E);
378 Value *VisitUnaryNot (const UnaryOperator *E);
379 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner9f0ad962007-08-24 21:20:17 +0000380 Value *VisitUnaryReal (const UnaryOperator *E);
381 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000382 Value *VisitUnaryExtension(const UnaryOperator *E) {
383 return Visit(E->getSubExpr());
384 }
Craig Toppera97d7e72013-07-26 06:16:11 +0000385
Anders Carlssona5d077d2009-04-14 16:58:56 +0000386 // C++
Douglas Gregor34f6c6d2011-08-09 00:37:14 +0000387 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
Eli Friedman0be39702011-08-14 04:50:34 +0000388 return EmitLoadOfLValue(E);
Douglas Gregor34f6c6d2011-08-09 00:37:14 +0000389 }
Craig Toppera97d7e72013-07-26 06:16:11 +0000390
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000391 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
392 return Visit(DAE->getExpr());
393 }
Richard Smith852c9db2013-04-20 22:23:05 +0000394 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
395 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
396 return Visit(DIE->getExpr());
397 }
Anders Carlssona5d077d2009-04-14 16:58:56 +0000398 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
399 return CGF.LoadCXXThis();
Mike Stump4a3999f2009-09-09 13:00:44 +0000400 }
401
John McCall5d413782010-12-06 08:20:24 +0000402 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall08ef4662011-11-10 08:15:53 +0000403 CGF.enterFullExpression(E);
404 CodeGenFunction::RunCleanupsScope Scope(CGF);
David Blaikie1b5adb82014-07-10 20:42:59 +0000405 return Visit(E->getSubExpr());
Anders Carlssonc82b86d2009-05-19 04:48:36 +0000406 }
Anders Carlsson4a7b49b2009-05-31 01:40:14 +0000407 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
408 return CGF.EmitCXXNewExpr(E);
409 }
Anders Carlsson81f0df92009-08-16 21:13:42 +0000410 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
411 CGF.EmitCXXDeleteExpr(E);
Craig Topper8a13c412014-05-21 05:09:00 +0000412 return nullptr;
Anders Carlsson81f0df92009-08-16 21:13:42 +0000413 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000414
Alp Tokercbb90342013-12-13 20:49:58 +0000415 Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
Francois Pichet34b21132010-12-08 22:35:30 +0000416 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet9dfa3ce2010-12-07 00:08:36 +0000417 }
418
John Wiegley6242b6a2011-04-28 00:16:57 +0000419 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
420 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
421 }
422
John Wiegleyf9f65842011-04-25 06:54:41 +0000423 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
424 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
425 }
426
Douglas Gregorad8a3362009-09-04 17:36:40 +0000427 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
428 // C++ [expr.pseudo]p1:
Mike Stump4a3999f2009-09-09 13:00:44 +0000429 // The result shall only be used as the operand for the function call
Douglas Gregorad8a3362009-09-04 17:36:40 +0000430 // operator (), and the result of such a call has type void. The only
431 // effect is the evaluation of the postfix-expression before the dot or
432 // arrow.
433 CGF.EmitScalarExpr(E->getBase());
Craig Topper8a13c412014-05-21 05:09:00 +0000434 return nullptr;
Douglas Gregorad8a3362009-09-04 17:36:40 +0000435 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000436
Anders Carlsson04c3bf42009-09-15 04:39:46 +0000437 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlsson5b944432010-05-22 17:45:10 +0000438 return EmitNullValue(E->getType());
Anders Carlsson04c3bf42009-09-15 04:39:46 +0000439 }
Anders Carlsson4b08db72009-10-30 01:42:31 +0000440
441 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
442 CGF.EmitCXXThrowExpr(E);
Craig Topper8a13c412014-05-21 05:09:00 +0000443 return nullptr;
Anders Carlsson4b08db72009-10-30 01:42:31 +0000444 }
445
Sebastian Redlb67655f2010-09-10 21:04:00 +0000446 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000447 return Builder.getInt1(E->getValue());
Sebastian Redlb67655f2010-09-10 21:04:00 +0000448 }
449
Chris Lattner2da04b32007-08-24 05:35:26 +0000450 // Binary Operators.
Chris Lattner2da04b32007-08-24 05:35:26 +0000451 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000452 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000453 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Chris Lattner51924e512010-06-26 21:25:03 +0000454 case LangOptions::SOB_Defined:
455 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
Richard Smith3e056de2012-08-25 00:32:28 +0000456 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000457 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith3e056de2012-08-25 00:32:28 +0000458 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
459 // Fall through.
Chris Lattner51924e512010-06-26 21:25:03 +0000460 case LangOptions::SOB_Trapping:
461 return EmitOverflowCheckedBinOp(Ops);
462 }
463 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000464
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000465 if (Ops.Ty->isUnsignedIntegerType() &&
466 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow))
Will Dietz1897cb32012-11-27 15:01:55 +0000467 return EmitOverflowCheckedBinOp(Ops);
468
Duncan Sands998f9d92010-02-15 16:14:01 +0000469 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner94dfae22009-06-17 06:36:24 +0000470 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner2da04b32007-08-24 05:35:26 +0000471 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
472 }
Mike Stump0c61b732009-04-01 20:28:16 +0000473 /// Create a binary op that checks for overflow.
474 /// Currently only supports +, - and *.
475 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Richard Smith4d1458e2012-09-08 02:08:36 +0000476
Chris Lattner8ee6a412010-09-11 21:47:09 +0000477 // Check for undefined division and modulus behaviors.
Craig Toppera97d7e72013-07-26 06:16:11 +0000478 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
Chris Lattner8ee6a412010-09-11 21:47:09 +0000479 llvm::Value *Zero,bool isDiv);
David Tweed042e0882013-01-07 16:43:27 +0000480 // Common helper for getting how wide LHS of shift is.
481 static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
Chris Lattner2da04b32007-08-24 05:35:26 +0000482 Value *EmitDiv(const BinOpInfo &Ops);
483 Value *EmitRem(const BinOpInfo &Ops);
484 Value *EmitAdd(const BinOpInfo &Ops);
485 Value *EmitSub(const BinOpInfo &Ops);
486 Value *EmitShl(const BinOpInfo &Ops);
487 Value *EmitShr(const BinOpInfo &Ops);
488 Value *EmitAnd(const BinOpInfo &Ops) {
489 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
490 }
491 Value *EmitXor(const BinOpInfo &Ops) {
492 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
493 }
494 Value *EmitOr (const BinOpInfo &Ops) {
495 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
496 }
497
Chris Lattner3d966d62007-08-24 21:00:35 +0000498 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor914af212010-04-23 04:16:32 +0000499 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
500 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +0000501 Value *&Result);
Douglas Gregor914af212010-04-23 04:16:32 +0000502
Chris Lattnerb6334692007-08-26 21:41:21 +0000503 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner3d966d62007-08-24 21:00:35 +0000504 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
505
506 // Binary operators and binary compound assignment operators.
507#define HANDLEBINOP(OP) \
Chris Lattnerb6334692007-08-26 21:41:21 +0000508 Value *VisitBin ## OP(const BinaryOperator *E) { \
509 return Emit ## OP(EmitBinOps(E)); \
510 } \
511 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
512 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner3d966d62007-08-24 21:00:35 +0000513 }
Daniel Dunbare017ecc2009-12-19 17:50:07 +0000514 HANDLEBINOP(Mul)
515 HANDLEBINOP(Div)
516 HANDLEBINOP(Rem)
517 HANDLEBINOP(Add)
518 HANDLEBINOP(Sub)
519 HANDLEBINOP(Shl)
520 HANDLEBINOP(Shr)
521 HANDLEBINOP(And)
522 HANDLEBINOP(Xor)
523 HANDLEBINOP(Or)
Chris Lattner3d966d62007-08-24 21:00:35 +0000524#undef HANDLEBINOP
Daniel Dunbarbfb1cd72008-08-06 02:00:38 +0000525
Chris Lattner2da04b32007-08-24 05:35:26 +0000526 // Comparisons.
527 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
528 unsigned SICmpOpc, unsigned FCmpOpc);
529#define VISITCOMP(CODE, UI, SI, FP) \
530 Value *VisitBin##CODE(const BinaryOperator *E) { \
531 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
532 llvm::FCmpInst::FP); }
Daniel Dunbare017ecc2009-12-19 17:50:07 +0000533 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
534 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
535 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
536 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
537 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
538 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner2da04b32007-08-24 05:35:26 +0000539#undef VISITCOMP
Mike Stump4a3999f2009-09-09 13:00:44 +0000540
Chris Lattner2da04b32007-08-24 05:35:26 +0000541 Value *VisitBinAssign (const BinaryOperator *E);
542
543 Value *VisitBinLAnd (const BinaryOperator *E);
544 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000545 Value *VisitBinComma (const BinaryOperator *E);
546
Eli Friedmanacfb1df2009-11-18 09:41:26 +0000547 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
548 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
549
Chris Lattner2da04b32007-08-24 05:35:26 +0000550 // Other Operators.
Mike Stumpab3afd82009-02-12 18:29:15 +0000551 Value *VisitBlockExpr(const BlockExpr *BE);
John McCallc07a0c72011-02-17 10:25:35 +0000552 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Chris Lattner2da04b32007-08-24 05:35:26 +0000553 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000554 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner2da04b32007-08-24 05:35:26 +0000555 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
556 return CGF.EmitObjCStringLiteral(E);
557 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000558 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
559 return CGF.EmitObjCBoxedExpr(E);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000560 }
561 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
562 return CGF.EmitObjCArrayLiteral(E);
563 }
564 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
565 return CGF.EmitObjCDictionaryLiteral(E);
566 }
Tanya Lattner55808c12011-06-04 00:47:47 +0000567 Value *VisitAsTypeExpr(AsTypeExpr *CE);
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000568 Value *VisitAtomicExpr(AtomicExpr *AE);
Chris Lattner2da04b32007-08-24 05:35:26 +0000569};
570} // end anonymous namespace.
571
572//===----------------------------------------------------------------------===//
573// Utilities
574//===----------------------------------------------------------------------===//
575
Chris Lattnere0044382007-08-26 16:42:57 +0000576/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner2e928882007-08-26 17:25:57 +0000577/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnere0044382007-08-26 16:42:57 +0000578Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCallb692a092009-10-22 20:10:53 +0000579 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stump4a3999f2009-09-09 13:00:44 +0000580
John McCall8cb679e2010-11-15 09:13:47 +0000581 if (SrcType->isRealFloatingType())
582 return EmitFloatToBoolConversion(Src);
Mike Stump4a3999f2009-09-09 13:00:44 +0000583
John McCall7a9aac22010-08-23 01:21:21 +0000584 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
585 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stump4a3999f2009-09-09 13:00:44 +0000586
Daniel Dunbaref957f32008-08-25 10:38:11 +0000587 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattnere0044382007-08-26 16:42:57 +0000588 "Unknown scalar type to convert");
Mike Stump4a3999f2009-09-09 13:00:44 +0000589
John McCall8cb679e2010-11-15 09:13:47 +0000590 if (isa<llvm::IntegerType>(Src->getType()))
591 return EmitIntToBoolConversion(Src);
Mike Stump4a3999f2009-09-09 13:00:44 +0000592
John McCall8cb679e2010-11-15 09:13:47 +0000593 assert(isa<llvm::PointerType>(Src->getType()));
594 return EmitPointerToBoolConversion(Src);
Chris Lattnere0044382007-08-26 16:42:57 +0000595}
596
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000597void ScalarExprEmitter::EmitFloatConversionCheck(Value *OrigSrc,
598 QualType OrigSrcType,
599 Value *Src, QualType SrcType,
600 QualType DstType,
601 llvm::Type *DstTy) {
Alexey Samsonov24cad992014-07-17 18:46:27 +0000602 CodeGenFunction::SanitizerScope SanScope(&CGF);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000603 using llvm::APFloat;
604 using llvm::APSInt;
605
606 llvm::Type *SrcTy = Src->getType();
607
Craig Topper8a13c412014-05-21 05:09:00 +0000608 llvm::Value *Check = nullptr;
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000609 if (llvm::IntegerType *IntTy = dyn_cast<llvm::IntegerType>(SrcTy)) {
610 // Integer to floating-point. This can fail for unsigned short -> __half
611 // or unsigned __int128 -> float.
612 assert(DstType->isFloatingType());
613 bool SrcIsUnsigned = OrigSrcType->isUnsignedIntegerOrEnumerationType();
614
615 APFloat LargestFloat =
616 APFloat::getLargest(CGF.getContext().getFloatTypeSemantics(DstType));
617 APSInt LargestInt(IntTy->getBitWidth(), SrcIsUnsigned);
618
619 bool IsExact;
620 if (LargestFloat.convertToInteger(LargestInt, APFloat::rmTowardZero,
621 &IsExact) != APFloat::opOK)
622 // The range of representable values of this floating point type includes
623 // all values of this integer type. Don't need an overflow check.
624 return;
625
626 llvm::Value *Max = llvm::ConstantInt::get(VMContext, LargestInt);
627 if (SrcIsUnsigned)
628 Check = Builder.CreateICmpULE(Src, Max);
629 else {
630 llvm::Value *Min = llvm::ConstantInt::get(VMContext, -LargestInt);
631 llvm::Value *GE = Builder.CreateICmpSGE(Src, Min);
632 llvm::Value *LE = Builder.CreateICmpSLE(Src, Max);
633 Check = Builder.CreateAnd(GE, LE);
634 }
635 } else {
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000636 const llvm::fltSemantics &SrcSema =
637 CGF.getContext().getFloatTypeSemantics(OrigSrcType);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000638 if (isa<llvm::IntegerType>(DstTy)) {
Richard Smith2b01d502013-03-27 23:20:25 +0000639 // Floating-point to integer. This has undefined behavior if the source is
640 // +-Inf, NaN, or doesn't fit into the destination type (after truncation
641 // to an integer).
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000642 unsigned Width = CGF.getContext().getIntWidth(DstType);
643 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
644
645 APSInt Min = APSInt::getMinValue(Width, Unsigned);
Richard Smith2b01d502013-03-27 23:20:25 +0000646 APFloat MinSrc(SrcSema, APFloat::uninitialized);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000647 if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
648 APFloat::opOverflow)
649 // Don't need an overflow check for lower bound. Just check for
650 // -Inf/NaN.
Richard Smith4af40c42013-03-19 00:01:12 +0000651 MinSrc = APFloat::getInf(SrcSema, true);
652 else
653 // Find the largest value which is too small to represent (before
654 // truncation toward zero).
655 MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000656
657 APSInt Max = APSInt::getMaxValue(Width, Unsigned);
Richard Smith2b01d502013-03-27 23:20:25 +0000658 APFloat MaxSrc(SrcSema, APFloat::uninitialized);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000659 if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
660 APFloat::opOverflow)
661 // Don't need an overflow check for upper bound. Just check for
662 // +Inf/NaN.
Richard Smith4af40c42013-03-19 00:01:12 +0000663 MaxSrc = APFloat::getInf(SrcSema, false);
664 else
665 // Find the smallest value which is too large to represent (before
666 // truncation toward zero).
667 MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000668
Richard Smith2b01d502013-03-27 23:20:25 +0000669 // If we're converting from __half, convert the range to float to match
670 // the type of src.
671 if (OrigSrcType->isHalfType()) {
672 const llvm::fltSemantics &Sema =
673 CGF.getContext().getFloatTypeSemantics(SrcType);
674 bool IsInexact;
675 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
676 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
677 }
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000678
Richard Smith4af40c42013-03-19 00:01:12 +0000679 llvm::Value *GE =
680 Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
681 llvm::Value *LE =
682 Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
683 Check = Builder.CreateAnd(GE, LE);
684 } else {
Richard Smith2b01d502013-03-27 23:20:25 +0000685 // FIXME: Maybe split this sanitizer out from float-cast-overflow.
686 //
687 // Floating-point to floating-point. This has undefined behavior if the
688 // source is not in the range of representable values of the destination
689 // type. The C and C++ standards are spectacularly unclear here. We
690 // diagnose finite out-of-range conversions, but allow infinities and NaNs
691 // to convert to the corresponding value in the smaller type.
692 //
693 // C11 Annex F gives all such conversions defined behavior for IEC 60559
694 // conforming implementations. Unfortunately, LLVM's fptrunc instruction
695 // does not.
696
697 // Converting from a lower rank to a higher rank can never have
698 // undefined behavior, since higher-rank types must have a superset
699 // of values of lower-rank types.
700 if (CGF.getContext().getFloatingTypeOrder(OrigSrcType, DstType) != 1)
701 return;
702
703 assert(!OrigSrcType->isHalfType() &&
704 "should not check conversion from __half, it has the lowest rank");
705
706 const llvm::fltSemantics &DstSema =
707 CGF.getContext().getFloatTypeSemantics(DstType);
708 APFloat MinBad = APFloat::getLargest(DstSema, false);
709 APFloat MaxBad = APFloat::getInf(DstSema, false);
710
711 bool IsInexact;
712 MinBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
713 MaxBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
714
715 Value *AbsSrc = CGF.EmitNounwindRuntimeCall(
716 CGF.CGM.getIntrinsic(llvm::Intrinsic::fabs, Src->getType()), Src);
Richard Smith4af40c42013-03-19 00:01:12 +0000717 llvm::Value *GE =
Richard Smith2b01d502013-03-27 23:20:25 +0000718 Builder.CreateFCmpOGT(AbsSrc, llvm::ConstantFP::get(VMContext, MinBad));
Richard Smith4af40c42013-03-19 00:01:12 +0000719 llvm::Value *LE =
Richard Smith2b01d502013-03-27 23:20:25 +0000720 Builder.CreateFCmpOLT(AbsSrc, llvm::ConstantFP::get(VMContext, MaxBad));
721 Check = Builder.CreateNot(Builder.CreateAnd(GE, LE));
Richard Smith4af40c42013-03-19 00:01:12 +0000722 }
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000723 }
724
725 // FIXME: Provide a SourceLocation.
726 llvm::Constant *StaticArgs[] = {
727 CGF.EmitCheckTypeDescriptor(OrigSrcType),
728 CGF.EmitCheckTypeDescriptor(DstType)
729 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000730 CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow),
731 "float_cast_overflow", StaticArgs, OrigSrc);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000732}
733
Chris Lattner3474c202007-08-26 06:48:56 +0000734/// EmitScalarConversion - Emit a conversion from the specified type to the
735/// specified destination type, both of which are LLVM scalar types.
Chris Lattner42e6b812007-08-26 16:34:22 +0000736Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
737 QualType DstType) {
Chris Lattner0f398c42008-07-26 22:37:01 +0000738 SrcType = CGF.getContext().getCanonicalType(SrcType);
739 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3474c202007-08-26 06:48:56 +0000740 if (SrcType == DstType) return Src;
Mike Stump4a3999f2009-09-09 13:00:44 +0000741
Craig Topper8a13c412014-05-21 05:09:00 +0000742 if (DstType->isVoidType()) return nullptr;
Mike Stump4a3999f2009-09-09 13:00:44 +0000743
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000744 llvm::Value *OrigSrc = Src;
745 QualType OrigSrcType = SrcType;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000746 llvm::Type *SrcTy = Src->getType();
747
Ahmed Bougacha47ec2c72015-03-23 17:48:07 +0000748 // Handle conversions to bool first, they are special: comparisons against 0.
749 if (DstType->isBooleanType())
750 return EmitConversionToBool(Src, SrcType);
751
752 llvm::Type *DstTy = ConvertType(DstType);
753
754 // Cast from storage-only half FP using the special intrinsic.
Oliver Stannarded8ecc82014-08-27 16:31:57 +0000755 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
756 !CGF.getContext().getLangOpts().HalfArgsAndReturns) {
Ahmed Bougacha47ec2c72015-03-23 17:48:07 +0000757 if (DstTy->isFloatingPointTy())
758 return Builder.CreateCall(
759 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, DstTy), Src);
760
761 // If this isn't an FP->FP conversion, go through float.
Tim Northover6dbcbac2014-07-17 10:51:31 +0000762 Src = Builder.CreateCall(
763 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
764 CGF.CGM.FloatTy),
765 Src);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000766 SrcType = CGF.getContext().FloatTy;
Chris Lattnerece04092012-02-07 00:39:47 +0000767 SrcTy = CGF.FloatTy;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000768 }
769
Chris Lattner3474c202007-08-26 06:48:56 +0000770 // Ignore conversions like int -> uint.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000771 if (SrcTy == DstTy)
Chris Lattner3474c202007-08-26 06:48:56 +0000772 return Src;
773
Mike Stump4a3999f2009-09-09 13:00:44 +0000774 // Handle pointer conversions next: pointers can only be converted to/from
775 // other pointers and integers. Check for pointer types in terms of LLVM, as
776 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar427f8732008-08-25 09:51:32 +0000777 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3474c202007-08-26 06:48:56 +0000778 // The source value may be an integer, or a pointer.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000779 if (isa<llvm::PointerType>(SrcTy))
Chris Lattner3474c202007-08-26 06:48:56 +0000780 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson12f5a252009-09-12 04:57:16 +0000781
Chris Lattner3474c202007-08-26 06:48:56 +0000782 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman42d2a3a2009-03-04 04:02:35 +0000783 // First, convert to the correct width so that we control the kind of
784 // extension.
Chris Lattner2192fe52011-07-18 04:24:23 +0000785 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000786 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Eli Friedman42d2a3a2009-03-04 04:02:35 +0000787 llvm::Value* IntResult =
788 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
789 // Then, cast to pointer.
790 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +0000791 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000792
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000793 if (isa<llvm::PointerType>(SrcTy)) {
Chris Lattner3474c202007-08-26 06:48:56 +0000794 // Must be an ptr to int cast.
795 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlssone89b84a2007-10-31 23:18:02 +0000796 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +0000797 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000798
Nate Begemance4d7fc2008-04-18 23:10:10 +0000799 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman5ec4b312009-08-10 23:49:36 +0000800 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begemanb699c9b2009-01-18 06:42:49 +0000801 // Cast the scalar to element type
John McCall9dd450b2009-09-21 23:43:11 +0000802 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begemanb699c9b2009-01-18 06:42:49 +0000803 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
804
Nate Begemanb699c9b2009-01-18 06:42:49 +0000805 // Splat the element across to all elements
Nate Begemanb699c9b2009-01-18 06:42:49 +0000806 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Benjamin Kramer7a14bc02013-01-01 20:08:10 +0000807 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
Nate Begemanb699c9b2009-01-18 06:42:49 +0000808 }
Nate Begeman330aaa72007-12-30 02:59:45 +0000809
Chris Lattner6cba8e92008-02-02 04:51:41 +0000810 // Allow bitcast from vector to integer/fp of the same size.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000811 if (isa<llvm::VectorType>(SrcTy) ||
Chris Lattner6cba8e92008-02-02 04:51:41 +0000812 isa<llvm::VectorType>(DstTy))
Anders Carlssona297e7a2007-12-05 07:36:10 +0000813 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stump4a3999f2009-09-09 13:00:44 +0000814
Chris Lattner3474c202007-08-26 06:48:56 +0000815 // Finally, we have the arithmetic types: real int/float.
Craig Topper8a13c412014-05-21 05:09:00 +0000816 Value *Res = nullptr;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000817 llvm::Type *ResTy = DstTy;
818
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000819 // An overflowing conversion has undefined behavior if either the source type
820 // or the destination type is a floating-point type.
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000821 if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) &&
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000822 (OrigSrcType->isFloatingType() || DstType->isFloatingType()))
Will Dietzf54319c2013-01-18 11:30:38 +0000823 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType,
824 DstTy);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000825
Ahmed Bougacha47ec2c72015-03-23 17:48:07 +0000826 // Cast to half using the intrinsic if from FP type, through float otherwise.
Oliver Stannarded8ecc82014-08-27 16:31:57 +0000827 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
Ahmed Bougacha47ec2c72015-03-23 17:48:07 +0000828 !CGF.getContext().getLangOpts().HalfArgsAndReturns) {
829 if (SrcTy->isFloatingPointTy())
830 return Builder.CreateCall(
831 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, SrcTy), Src);
Chris Lattnerece04092012-02-07 00:39:47 +0000832 DstTy = CGF.FloatTy;
Ahmed Bougacha47ec2c72015-03-23 17:48:07 +0000833 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000834
835 if (isa<llvm::IntegerType>(SrcTy)) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000836 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Anders Carlssonc9d41e72007-12-26 18:20:19 +0000837 if (isa<llvm::IntegerType>(DstTy))
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000838 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
Anders Carlssonc9d41e72007-12-26 18:20:19 +0000839 else if (InputSigned)
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000840 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
Anders Carlssonc9d41e72007-12-26 18:20:19 +0000841 else
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000842 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
843 } else if (isa<llvm::IntegerType>(DstTy)) {
844 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000845 if (DstType->isSignedIntegerOrEnumerationType())
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000846 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
Anders Carlssonc9d41e72007-12-26 18:20:19 +0000847 else
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000848 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
849 } else {
850 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
851 "Unknown real conversion");
852 if (DstTy->getTypeID() < SrcTy->getTypeID())
853 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
854 else
855 Res = Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +0000856 }
857
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000858 if (DstTy != ResTy) {
859 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
Tim Northover6dbcbac2014-07-17 10:51:31 +0000860 Res = Builder.CreateCall(
861 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy),
862 Res);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000863 }
864
865 return Res;
Chris Lattner3474c202007-08-26 06:48:56 +0000866}
867
Mike Stump4a3999f2009-09-09 13:00:44 +0000868/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
869/// type to the specified destination type, where the destination type is an
870/// LLVM scalar type.
Chris Lattner42e6b812007-08-26 16:34:22 +0000871Value *ScalarExprEmitter::
872EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
873 QualType SrcTy, QualType DstTy) {
Chris Lattnerc141c1b2007-08-26 16:52:28 +0000874 // Get the source element type.
John McCall47fb9502013-03-07 21:37:08 +0000875 SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
Mike Stump4a3999f2009-09-09 13:00:44 +0000876
Chris Lattnerc141c1b2007-08-26 16:52:28 +0000877 // Handle conversions to bool first, they are special: comparisons against 0.
878 if (DstTy->isBooleanType()) {
879 // Complex != 0 -> (Real != 0) | (Imag != 0)
880 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
881 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
882 return Builder.CreateOr(Src.first, Src.second, "tobool");
883 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000884
Chris Lattner42e6b812007-08-26 16:34:22 +0000885 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
886 // the imaginary part of the complex value is discarded and the value of the
887 // real part is converted according to the conversion rules for the
Mike Stump4a3999f2009-09-09 13:00:44 +0000888 // corresponding real type.
Chris Lattner42e6b812007-08-26 16:34:22 +0000889 return EmitScalarConversion(Src.first, SrcTy, DstTy);
890}
891
Anders Carlsson5b944432010-05-22 17:45:10 +0000892Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
Richard Smithd82a2ce2012-12-21 03:17:28 +0000893 return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
Anders Carlsson5b944432010-05-22 17:45:10 +0000894}
Chris Lattner42e6b812007-08-26 16:34:22 +0000895
Richard Smithe30752c2012-10-09 19:52:38 +0000896/// \brief Emit a sanitization check for the given "binary" operation (which
897/// might actually be a unary increment which has been lowered to a binary
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000898/// operation). The check passes if all values in \p Checks (which are \c i1),
899/// are \c true.
900void ScalarExprEmitter::EmitBinOpCheck(
901 ArrayRef<std::pair<Value *, SanitizerKind>> Checks, const BinOpInfo &Info) {
Alexey Samsonov24cad992014-07-17 18:46:27 +0000902 assert(CGF.IsSanitizerScope);
Richard Smithe30752c2012-10-09 19:52:38 +0000903 StringRef CheckName;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000904 SmallVector<llvm::Constant *, 4> StaticData;
905 SmallVector<llvm::Value *, 2> DynamicData;
Richard Smithe30752c2012-10-09 19:52:38 +0000906
907 BinaryOperatorKind Opcode = Info.Opcode;
908 if (BinaryOperator::isCompoundAssignmentOp(Opcode))
909 Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
910
911 StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
912 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
913 if (UO && UO->getOpcode() == UO_Minus) {
914 CheckName = "negate_overflow";
915 StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
916 DynamicData.push_back(Info.RHS);
917 } else {
918 if (BinaryOperator::isShiftOp(Opcode)) {
919 // Shift LHS negative or too large, or RHS out of bounds.
920 CheckName = "shift_out_of_bounds";
921 const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
922 StaticData.push_back(
923 CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
924 StaticData.push_back(
925 CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
926 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
927 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
928 CheckName = "divrem_overflow";
Will Dietzcefb4482013-01-07 22:25:52 +0000929 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
Richard Smithe30752c2012-10-09 19:52:38 +0000930 } else {
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +0000931 // Arithmetic overflow (+, -, *).
Richard Smithe30752c2012-10-09 19:52:38 +0000932 switch (Opcode) {
933 case BO_Add: CheckName = "add_overflow"; break;
934 case BO_Sub: CheckName = "sub_overflow"; break;
935 case BO_Mul: CheckName = "mul_overflow"; break;
936 default: llvm_unreachable("unexpected opcode for bin op check");
937 }
Will Dietzcefb4482013-01-07 22:25:52 +0000938 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
Richard Smithe30752c2012-10-09 19:52:38 +0000939 }
940 DynamicData.push_back(Info.LHS);
941 DynamicData.push_back(Info.RHS);
942 }
943
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000944 CGF.EmitCheck(Checks, CheckName, StaticData, DynamicData);
Richard Smithe30752c2012-10-09 19:52:38 +0000945}
946
Chris Lattner2da04b32007-08-24 05:35:26 +0000947//===----------------------------------------------------------------------===//
948// Visitor Methods
949//===----------------------------------------------------------------------===//
950
951Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000952 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner2da04b32007-08-24 05:35:26 +0000953 if (E->getType()->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +0000954 return nullptr;
Owen Anderson7ec07a52009-07-30 23:11:26 +0000955 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner2da04b32007-08-24 05:35:26 +0000956}
957
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000958Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begemana0110022010-06-08 00:16:34 +0000959 // Vector Mask Case
Craig Toppera97d7e72013-07-26 06:16:11 +0000960 if (E->getNumSubExprs() == 2 ||
Rafael Espindola9cdbd9d2010-06-09 02:17:08 +0000961 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner5e016ae2010-06-27 07:15:29 +0000962 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
963 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
964 Value *Mask;
Craig Toppera97d7e72013-07-26 06:16:11 +0000965
Chris Lattner2192fe52011-07-18 04:24:23 +0000966 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
Nate Begemana0110022010-06-08 00:16:34 +0000967 unsigned LHSElts = LTy->getNumElements();
968
969 if (E->getNumSubExprs() == 3) {
970 Mask = CGF.EmitScalarExpr(E->getExpr(2));
Craig Toppera97d7e72013-07-26 06:16:11 +0000971
Nate Begemana0110022010-06-08 00:16:34 +0000972 // Shuffle LHS & RHS into one input vector.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000973 SmallVector<llvm::Constant*, 32> concat;
Nate Begemana0110022010-06-08 00:16:34 +0000974 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000975 concat.push_back(Builder.getInt32(2*i));
976 concat.push_back(Builder.getInt32(2*i+1));
Nate Begemana0110022010-06-08 00:16:34 +0000977 }
Craig Toppera97d7e72013-07-26 06:16:11 +0000978
Chris Lattner91c08ad2011-02-15 00:14:06 +0000979 Value* CV = llvm::ConstantVector::get(concat);
Nate Begemana0110022010-06-08 00:16:34 +0000980 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
981 LHSElts *= 2;
982 } else {
983 Mask = RHS;
984 }
Craig Toppera97d7e72013-07-26 06:16:11 +0000985
Chris Lattner2192fe52011-07-18 04:24:23 +0000986 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
Nate Begemana0110022010-06-08 00:16:34 +0000987 llvm::Constant* EltMask;
Craig Toppera97d7e72013-07-26 06:16:11 +0000988
Craig Topperb9b7ea62013-08-01 06:42:40 +0000989 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
990 llvm::NextPowerOf2(LHSElts-1)-1);
Craig Toppera97d7e72013-07-26 06:16:11 +0000991
Nate Begemana0110022010-06-08 00:16:34 +0000992 // Mask off the high bits of each shuffle index.
Chris Lattner2d6b7b92012-01-25 05:34:41 +0000993 Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
994 EltMask);
Nate Begemana0110022010-06-08 00:16:34 +0000995 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
Craig Toppera97d7e72013-07-26 06:16:11 +0000996
Nate Begemana0110022010-06-08 00:16:34 +0000997 // newv = undef
998 // mask = mask & maskbits
999 // for each elt
1000 // n = extract mask i
1001 // x = extract val n
1002 // newv = insert newv, x, i
Chris Lattner2192fe52011-07-18 04:24:23 +00001003 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
Craig Topper18243fb2013-07-27 05:00:42 +00001004 MTy->getNumElements());
Nate Begemana0110022010-06-08 00:16:34 +00001005 Value* NewV = llvm::UndefValue::get(RTy);
1006 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Michael J. Spencerdd597752014-05-31 00:22:12 +00001007 Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i);
Eli Friedman1fa36052012-04-05 21:48:40 +00001008 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
Craig Toppera97d7e72013-07-26 06:16:11 +00001009
Nate Begemana0110022010-06-08 00:16:34 +00001010 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
Eli Friedman1fa36052012-04-05 21:48:40 +00001011 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
Nate Begemana0110022010-06-08 00:16:34 +00001012 }
1013 return NewV;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001014 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001015
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001016 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
1017 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Craig Toppera97d7e72013-07-26 06:16:11 +00001018
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001019 SmallVector<llvm::Constant*, 32> indices;
Craig Topper0ed37bd2013-08-01 04:51:48 +00001020 for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
Craig Topper50ad5b72013-08-03 17:40:38 +00001021 llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
1022 // Check for -1 and output it as undef in the IR.
1023 if (Idx.isSigned() && Idx.isAllOnesValue())
1024 indices.push_back(llvm::UndefValue::get(CGF.Int32Ty));
1025 else
1026 indices.push_back(Builder.getInt32(Idx.getZExtValue()));
Nate Begemana0110022010-06-08 00:16:34 +00001027 }
1028
Chris Lattner91c08ad2011-02-15 00:14:06 +00001029 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001030 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
1031}
Hal Finkelc4d7c822013-09-18 03:29:45 +00001032
1033Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
1034 QualType SrcType = E->getSrcExpr()->getType(),
1035 DstType = E->getType();
1036
1037 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
1038
1039 SrcType = CGF.getContext().getCanonicalType(SrcType);
1040 DstType = CGF.getContext().getCanonicalType(DstType);
1041 if (SrcType == DstType) return Src;
1042
1043 assert(SrcType->isVectorType() &&
1044 "ConvertVector source type must be a vector");
1045 assert(DstType->isVectorType() &&
1046 "ConvertVector destination type must be a vector");
1047
1048 llvm::Type *SrcTy = Src->getType();
1049 llvm::Type *DstTy = ConvertType(DstType);
1050
1051 // Ignore conversions like int -> uint.
1052 if (SrcTy == DstTy)
1053 return Src;
1054
1055 QualType SrcEltType = SrcType->getAs<VectorType>()->getElementType(),
1056 DstEltType = DstType->getAs<VectorType>()->getElementType();
1057
1058 assert(SrcTy->isVectorTy() &&
1059 "ConvertVector source IR type must be a vector");
1060 assert(DstTy->isVectorTy() &&
1061 "ConvertVector destination IR type must be a vector");
1062
1063 llvm::Type *SrcEltTy = SrcTy->getVectorElementType(),
1064 *DstEltTy = DstTy->getVectorElementType();
1065
1066 if (DstEltType->isBooleanType()) {
1067 assert((SrcEltTy->isFloatingPointTy() ||
1068 isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
1069
1070 llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
1071 if (SrcEltTy->isFloatingPointTy()) {
1072 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
1073 } else {
1074 return Builder.CreateICmpNE(Src, Zero, "tobool");
1075 }
1076 }
1077
1078 // We have the arithmetic types: real int/float.
Craig Topper8a13c412014-05-21 05:09:00 +00001079 Value *Res = nullptr;
Hal Finkelc4d7c822013-09-18 03:29:45 +00001080
1081 if (isa<llvm::IntegerType>(SrcEltTy)) {
1082 bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
1083 if (isa<llvm::IntegerType>(DstEltTy))
1084 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1085 else if (InputSigned)
1086 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1087 else
1088 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1089 } else if (isa<llvm::IntegerType>(DstEltTy)) {
1090 assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
1091 if (DstEltType->isSignedIntegerOrEnumerationType())
1092 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1093 else
1094 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1095 } else {
1096 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
1097 "Unknown real conversion");
1098 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
1099 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1100 else
1101 Res = Builder.CreateFPExt(Src, DstTy, "conv");
1102 }
1103
1104 return Res;
1105}
1106
Eli Friedmancb422f12009-11-26 03:22:21 +00001107Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
Richard Smith5fab0c92011-12-28 19:48:30 +00001108 llvm::APSInt Value;
1109 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
Eli Friedmancb422f12009-11-26 03:22:21 +00001110 if (E->isArrow())
1111 CGF.EmitScalarExpr(E->getBase());
1112 else
1113 EmitLValue(E->getBase());
Richard Smith5fab0c92011-12-28 19:48:30 +00001114 return Builder.getInt(Value);
Eli Friedmancb422f12009-11-26 03:22:21 +00001115 }
Devang Patel44b8bf02010-10-04 21:46:04 +00001116
Eli Friedmancb422f12009-11-26 03:22:21 +00001117 return EmitLoadOfLValue(E);
1118}
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001119
Chris Lattner2da04b32007-08-24 05:35:26 +00001120Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00001121 TestAndClearIgnoreResultAssign();
1122
Chris Lattner2da04b32007-08-24 05:35:26 +00001123 // Emit subscript expressions in rvalue context's. For most cases, this just
1124 // loads the lvalue formed by the subscript expr. However, we have to be
1125 // careful, because the base of a vector subscript is occasionally an rvalue,
1126 // so we can't get it as an lvalue.
1127 if (!E->getBase()->getType()->isVectorType())
1128 return EmitLoadOfLValue(E);
Mike Stump4a3999f2009-09-09 13:00:44 +00001129
Chris Lattner2da04b32007-08-24 05:35:26 +00001130 // Handle the vector case. The base must be a vector, the index must be an
1131 // integer value.
1132 Value *Base = Visit(E->getBase());
1133 Value *Idx = Visit(E->getIdx());
Richard Smith539e4a72013-02-23 02:53:19 +00001134 QualType IdxTy = E->getIdx()->getType();
1135
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001136 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00001137 CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
1138
Chris Lattner2da04b32007-08-24 05:35:26 +00001139 return Builder.CreateExtractElement(Base, Idx, "vecext");
1140}
1141
Nate Begeman19351632009-10-18 20:10:40 +00001142static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
Chris Lattner2192fe52011-07-18 04:24:23 +00001143 unsigned Off, llvm::Type *I32Ty) {
Nate Begeman19351632009-10-18 20:10:40 +00001144 int MV = SVI->getMaskValue(Idx);
Craig Toppera97d7e72013-07-26 06:16:11 +00001145 if (MV == -1)
Nate Begeman19351632009-10-18 20:10:40 +00001146 return llvm::UndefValue::get(I32Ty);
1147 return llvm::ConstantInt::get(I32Ty, Off+MV);
1148}
1149
1150Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1151 bool Ignore = TestAndClearIgnoreResultAssign();
1152 (void)Ignore;
1153 assert (Ignore == false && "init list ignored");
1154 unsigned NumInitElements = E->getNumInits();
Craig Toppera97d7e72013-07-26 06:16:11 +00001155
Nate Begeman19351632009-10-18 20:10:40 +00001156 if (E->hadArrayRangeDesignator())
1157 CGF.ErrorUnsupported(E, "GNU array range designator extension");
Craig Toppera97d7e72013-07-26 06:16:11 +00001158
Chris Lattner2192fe52011-07-18 04:24:23 +00001159 llvm::VectorType *VType =
Nate Begeman19351632009-10-18 20:10:40 +00001160 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
Craig Toppera97d7e72013-07-26 06:16:11 +00001161
Sebastian Redl12757ab2011-09-24 17:48:14 +00001162 if (!VType) {
1163 if (NumInitElements == 0) {
1164 // C++11 value-initialization for the scalar.
1165 return EmitNullValue(E->getType());
1166 }
1167 // We have a scalar in braces. Just use the first element.
Nate Begeman19351632009-10-18 20:10:40 +00001168 return Visit(E->getInit(0));
Sebastian Redl12757ab2011-09-24 17:48:14 +00001169 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001170
Nate Begeman19351632009-10-18 20:10:40 +00001171 unsigned ResElts = VType->getNumElements();
Craig Toppera97d7e72013-07-26 06:16:11 +00001172
1173 // Loop over initializers collecting the Value for each, and remembering
Nate Begeman19351632009-10-18 20:10:40 +00001174 // whether the source was swizzle (ExtVectorElementExpr). This will allow
1175 // us to fold the shuffle for the swizzle into the shuffle for the vector
1176 // initializer, since LLVM optimizers generally do not want to touch
1177 // shuffles.
1178 unsigned CurIdx = 0;
1179 bool VIsUndefShuffle = false;
1180 llvm::Value *V = llvm::UndefValue::get(VType);
1181 for (unsigned i = 0; i != NumInitElements; ++i) {
1182 Expr *IE = E->getInit(i);
1183 Value *Init = Visit(IE);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001184 SmallVector<llvm::Constant*, 16> Args;
Craig Toppera97d7e72013-07-26 06:16:11 +00001185
Chris Lattner2192fe52011-07-18 04:24:23 +00001186 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001187
Nate Begeman19351632009-10-18 20:10:40 +00001188 // Handle scalar elements. If the scalar initializer is actually one
Craig Toppera97d7e72013-07-26 06:16:11 +00001189 // element of a different vector of the same width, use shuffle instead of
Nate Begeman19351632009-10-18 20:10:40 +00001190 // extract+insert.
1191 if (!VVT) {
1192 if (isa<ExtVectorElementExpr>(IE)) {
1193 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1194
1195 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
1196 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
Craig Topper8a13c412014-05-21 05:09:00 +00001197 Value *LHS = nullptr, *RHS = nullptr;
Nate Begeman19351632009-10-18 20:10:40 +00001198 if (CurIdx == 0) {
1199 // insert into undef -> shuffle (src, undef)
1200 Args.push_back(C);
Benjamin Kramer8001f742012-02-14 12:06:21 +00001201 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001202
1203 LHS = EI->getVectorOperand();
1204 RHS = V;
1205 VIsUndefShuffle = true;
1206 } else if (VIsUndefShuffle) {
1207 // insert into undefshuffle && size match -> shuffle (v, src)
1208 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1209 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner5e016ae2010-06-27 07:15:29 +00001210 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
Chris Lattner2531eb42011-04-19 22:55:03 +00001211 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001212 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1213
Nate Begeman19351632009-10-18 20:10:40 +00001214 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1215 RHS = EI->getVectorOperand();
1216 VIsUndefShuffle = false;
1217 }
1218 if (!Args.empty()) {
Chris Lattner91c08ad2011-02-15 00:14:06 +00001219 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman19351632009-10-18 20:10:40 +00001220 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
1221 ++CurIdx;
1222 continue;
1223 }
1224 }
1225 }
Chris Lattner2531eb42011-04-19 22:55:03 +00001226 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1227 "vecinit");
Nate Begeman19351632009-10-18 20:10:40 +00001228 VIsUndefShuffle = false;
1229 ++CurIdx;
1230 continue;
1231 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001232
Nate Begeman19351632009-10-18 20:10:40 +00001233 unsigned InitElts = VVT->getNumElements();
1234
Craig Toppera97d7e72013-07-26 06:16:11 +00001235 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
Nate Begeman19351632009-10-18 20:10:40 +00001236 // input is the same width as the vector being constructed, generate an
1237 // optimized shuffle of the swizzle input into the result.
Nate Begemanb8326be2009-10-25 02:26:01 +00001238 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman19351632009-10-18 20:10:40 +00001239 if (isa<ExtVectorElementExpr>(IE)) {
1240 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1241 Value *SVOp = SVI->getOperand(0);
Chris Lattner2192fe52011-07-18 04:24:23 +00001242 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001243
Nate Begeman19351632009-10-18 20:10:40 +00001244 if (OpTy->getNumElements() == ResElts) {
Nate Begeman19351632009-10-18 20:10:40 +00001245 for (unsigned j = 0; j != CurIdx; ++j) {
1246 // If the current vector initializer is a shuffle with undef, merge
1247 // this shuffle directly into it.
1248 if (VIsUndefShuffle) {
1249 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner5e016ae2010-06-27 07:15:29 +00001250 CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001251 } else {
Chris Lattner2531eb42011-04-19 22:55:03 +00001252 Args.push_back(Builder.getInt32(j));
Nate Begeman19351632009-10-18 20:10:40 +00001253 }
1254 }
1255 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner5e016ae2010-06-27 07:15:29 +00001256 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001257 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001258
1259 if (VIsUndefShuffle)
1260 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1261
1262 Init = SVOp;
1263 }
1264 }
1265
1266 // Extend init to result vector length, and then shuffle its contribution
1267 // to the vector initializer into V.
1268 if (Args.empty()) {
1269 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner2531eb42011-04-19 22:55:03 +00001270 Args.push_back(Builder.getInt32(j));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001271 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001272 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman19351632009-10-18 20:10:40 +00001273 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemanb8326be2009-10-25 02:26:01 +00001274 Mask, "vext");
Nate Begeman19351632009-10-18 20:10:40 +00001275
1276 Args.clear();
1277 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner2531eb42011-04-19 22:55:03 +00001278 Args.push_back(Builder.getInt32(j));
Nate Begeman19351632009-10-18 20:10:40 +00001279 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner2531eb42011-04-19 22:55:03 +00001280 Args.push_back(Builder.getInt32(j+Offset));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001281 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001282 }
1283
1284 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1285 // merging subsequent shuffles into this one.
1286 if (CurIdx == 0)
1287 std::swap(V, Init);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001288 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman19351632009-10-18 20:10:40 +00001289 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
1290 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1291 CurIdx += InitElts;
1292 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001293
Nate Begeman19351632009-10-18 20:10:40 +00001294 // FIXME: evaluate codegen vs. shuffling against constant null vector.
1295 // Emit remaining default initializers.
Chris Lattner2192fe52011-07-18 04:24:23 +00001296 llvm::Type *EltTy = VType->getElementType();
Craig Toppera97d7e72013-07-26 06:16:11 +00001297
Nate Begeman19351632009-10-18 20:10:40 +00001298 // Emit remaining default initializers
1299 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner2531eb42011-04-19 22:55:03 +00001300 Value *Idx = Builder.getInt32(CurIdx);
Nate Begeman19351632009-10-18 20:10:40 +00001301 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1302 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1303 }
1304 return V;
1305}
1306
Anders Carlsson8c793172009-11-23 17:57:54 +00001307static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
1308 const Expr *E = CE->getSubExpr();
John McCalld9c7c6562010-03-30 23:58:03 +00001309
John McCalle3027922010-08-25 11:45:40 +00001310 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCalld9c7c6562010-03-30 23:58:03 +00001311 return false;
Craig Toppera97d7e72013-07-26 06:16:11 +00001312
Anders Carlsson8c793172009-11-23 17:57:54 +00001313 if (isa<CXXThisExpr>(E)) {
1314 // We always assume that 'this' is never null.
1315 return false;
1316 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001317
Anders Carlsson8c793172009-11-23 17:57:54 +00001318 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001319 // And that glvalue casts are never null.
John McCall2536c6d2010-08-25 10:28:54 +00001320 if (ICE->getValueKind() != VK_RValue)
Anders Carlsson8c793172009-11-23 17:57:54 +00001321 return false;
1322 }
1323
1324 return true;
1325}
1326
Chris Lattner2da04b32007-08-24 05:35:26 +00001327// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1328// have to handle a more broad range of conversions than explicit casts, as they
1329// handle things like function to ptr-to-function decay etc.
John McCall23c29fe2011-06-24 21:55:10 +00001330Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Eli Friedmane96f1d32009-11-27 04:41:50 +00001331 Expr *E = CE->getSubExpr();
Anders Carlsson8c978b42009-09-22 22:00:46 +00001332 QualType DestTy = CE->getType();
John McCalle3027922010-08-25 11:45:40 +00001333 CastKind Kind = CE->getCastKind();
Craig Toppera97d7e72013-07-26 06:16:11 +00001334
Mike Stumpdf0fe272009-05-29 15:46:01 +00001335 if (!DestTy->isVoidType())
1336 TestAndClearIgnoreResultAssign();
Mike Stump4a3999f2009-09-09 13:00:44 +00001337
Eli Friedman0dfc6802009-11-27 02:07:44 +00001338 // Since almost all cast kinds apply to scalars, this switch doesn't have
1339 // a default case, so the compiler will warn on a missing case. The cases
1340 // are in the same order as in the CastKind enum.
Anders Carlsson3df53bc2009-08-24 18:26:39 +00001341 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +00001342 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
Eli Friedman34866c72012-08-31 00:14:07 +00001343 case CK_BuiltinFnToFnPtr:
1344 llvm_unreachable("builtin functions are handled elsewhere");
1345
Craig Toppera97d7e72013-07-26 06:16:11 +00001346 case CK_LValueBitCast:
John McCalle3027922010-08-25 11:45:40 +00001347 case CK_ObjCObjectLValueCast: {
Douglas Gregor51954272010-07-13 23:17:26 +00001348 Value *V = EmitLValue(E).getAddress();
Craig Toppera97d7e72013-07-26 06:16:11 +00001349 V = Builder.CreateBitCast(V,
Douglas Gregor51954272010-07-13 23:17:26 +00001350 ConvertType(CGF.getContext().getPointerType(DestTy)));
Nick Lewycky2d84e842013-10-02 02:29:49 +00001351 return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy),
1352 CE->getExprLoc());
Douglas Gregor51954272010-07-13 23:17:26 +00001353 }
John McCallcd78e802011-09-10 01:16:55 +00001354
John McCall9320b872011-09-09 05:25:32 +00001355 case CK_CPointerToObjCPointerCast:
1356 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00001357 case CK_AnyPointerToBlockPointerCast:
1358 case CK_BitCast: {
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001359 Value *Src = Visit(const_cast<Expr*>(E));
David Tweede1468322013-12-11 13:39:46 +00001360 llvm::Type *SrcTy = Src->getType();
1361 llvm::Type *DstTy = ConvertType(DestTy);
Bob Wilson95a27b02014-02-17 19:20:59 +00001362 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
David Tweede1468322013-12-11 13:39:46 +00001363 SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00001364 llvm_unreachable("wrong cast for pointers in different address spaces"
1365 "(must be an address space cast)!");
David Tweede1468322013-12-11 13:39:46 +00001366 }
Peter Collingbourned2926c92015-03-14 02:42:25 +00001367
1368 if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
1369 if (auto PT = DestTy->getAs<PointerType>())
1370 CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Src,
1371 /*MayBeNull=*/true);
1372 }
1373
David Tweede1468322013-12-11 13:39:46 +00001374 return Builder.CreateBitCast(Src, DstTy);
1375 }
1376 case CK_AddressSpaceConversion: {
1377 Value *Src = Visit(const_cast<Expr*>(E));
1378 return Builder.CreateAddrSpaceCast(Src, ConvertType(DestTy));
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001379 }
David Chisnallfa35df62012-01-16 17:27:18 +00001380 case CK_AtomicToNonAtomic:
1381 case CK_NonAtomicToAtomic:
John McCalle3027922010-08-25 11:45:40 +00001382 case CK_NoOp:
1383 case CK_UserDefinedConversion:
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001384 return Visit(const_cast<Expr*>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001385
John McCalle3027922010-08-25 11:45:40 +00001386 case CK_BaseToDerived: {
Jordan Rose7bb26112012-10-03 01:08:28 +00001387 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
1388 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
1389
Richard Smith2c5868c2013-02-13 21:18:23 +00001390 llvm::Value *V = Visit(E);
1391
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00001392 llvm::Value *Derived =
1393 CGF.GetAddressOfDerivedClass(V, DerivedClassDecl,
1394 CE->path_begin(), CE->path_end(),
1395 ShouldNullCheckClassCastValue(CE));
1396
Richard Smith2c5868c2013-02-13 21:18:23 +00001397 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
1398 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00001399 if (CGF.sanitizePerformTypeCheck())
Richard Smith2c5868c2013-02-13 21:18:23 +00001400 CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00001401 Derived, DestTy->getPointeeType());
Richard Smith2c5868c2013-02-13 21:18:23 +00001402
Peter Collingbourned2926c92015-03-14 02:42:25 +00001403 if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast))
1404 CGF.EmitVTablePtrCheckForCast(DestTy->getPointeeType(), Derived,
1405 /*MayBeNull=*/true);
1406
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00001407 return Derived;
Anders Carlsson8c793172009-11-23 17:57:54 +00001408 }
John McCalle3027922010-08-25 11:45:40 +00001409 case CK_UncheckedDerivedToBase:
1410 case CK_DerivedToBase: {
Jordan Rose7bb26112012-10-03 01:08:28 +00001411 const CXXRecordDecl *DerivedClassDecl =
1412 E->getType()->getPointeeCXXRecordDecl();
1413 assert(DerivedClassDecl && "DerivedToBase arg isn't a C++ object pointer!");
Anders Carlsson12f5a252009-09-12 04:57:16 +00001414
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00001415 return CGF.GetAddressOfBaseClass(
1416 Visit(E), DerivedClassDecl, CE->path_begin(), CE->path_end(),
1417 ShouldNullCheckClassCastValue(CE), CE->getExprLoc());
Anders Carlsson12f5a252009-09-12 04:57:16 +00001418 }
Anders Carlsson8a01a752011-04-11 02:03:26 +00001419 case CK_Dynamic: {
Eli Friedman0dfc6802009-11-27 02:07:44 +00001420 Value *V = Visit(const_cast<Expr*>(E));
1421 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1422 return CGF.EmitDynamicCast(V, DCE);
1423 }
Eli Friedmane96f1d32009-11-27 04:41:50 +00001424
John McCalle3027922010-08-25 11:45:40 +00001425 case CK_ArrayToPointerDecay: {
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001426 assert(E->getType()->isArrayType() &&
1427 "Array to pointer decay must have array source type!");
1428
1429 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1430
1431 // Note that VLA pointers are always decayed, so we don't need to do
1432 // anything here.
1433 if (!E->getType()->isVariableArrayType()) {
1434 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
David Majnemer17e26332014-12-14 12:16:43 +00001435 V = CGF.Builder.CreatePointerCast(
Pekka Jaaskelainene94b0e12014-12-19 18:04:27 +00001436 V, ConvertType(E->getType())->getPointerTo(
1437 V->getType()->getPointerAddressSpace()));
David Majnemer17e26332014-12-14 12:16:43 +00001438
1439 assert(isa<llvm::ArrayType>(V->getType()->getPointerElementType()) &&
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001440 "Expected pointer to array");
1441 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1442 }
1443
Chris Lattner71bd0c32011-07-20 04:31:01 +00001444 // Make sure the array decay ends up being the right type. This matters if
1445 // the array type was of an incomplete type.
David Tweede1468322013-12-11 13:39:46 +00001446 return CGF.Builder.CreatePointerCast(V, ConvertType(CE->getType()));
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001447 }
John McCalle3027922010-08-25 11:45:40 +00001448 case CK_FunctionToPointerDecay:
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001449 return EmitLValue(E).getAddress();
1450
John McCalle84af4e2010-11-13 01:35:44 +00001451 case CK_NullToPointer:
1452 if (MustVisitNullValue(E))
1453 (void) Visit(E);
1454
1455 return llvm::ConstantPointerNull::get(
1456 cast<llvm::PointerType>(ConvertType(DestTy)));
1457
John McCalle3027922010-08-25 11:45:40 +00001458 case CK_NullToMemberPointer: {
John McCalle84af4e2010-11-13 01:35:44 +00001459 if (MustVisitNullValue(E))
John McCalla1dee5302010-08-22 10:59:02 +00001460 (void) Visit(E);
1461
John McCall7a9aac22010-08-23 01:21:21 +00001462 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1463 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1464 }
Anders Carlsson12f5a252009-09-12 04:57:16 +00001465
John McCallc62bb392012-02-15 01:22:51 +00001466 case CK_ReinterpretMemberPointer:
John McCalle3027922010-08-25 11:45:40 +00001467 case CK_BaseToDerivedMemberPointer:
1468 case CK_DerivedToBaseMemberPointer: {
Eli Friedmane96f1d32009-11-27 04:41:50 +00001469 Value *Src = Visit(E);
Craig Toppera97d7e72013-07-26 06:16:11 +00001470
John McCalla1dee5302010-08-22 10:59:02 +00001471 // Note that the AST doesn't distinguish between checked and
1472 // unchecked member pointer conversions, so we always have to
1473 // implement checked conversions here. This is inefficient when
1474 // actual control flow may be required in order to perform the
1475 // check, which it is for data member pointers (but not member
1476 // function pointers on Itanium and ARM).
John McCall7a9aac22010-08-23 01:21:21 +00001477 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmane96f1d32009-11-27 04:41:50 +00001478 }
John McCall31168b02011-06-15 23:02:42 +00001479
John McCall2d637d22011-09-10 06:18:15 +00001480 case CK_ARCProduceObject:
John McCall31168b02011-06-15 23:02:42 +00001481 return CGF.EmitARCRetainScalarExpr(E);
John McCall2d637d22011-09-10 06:18:15 +00001482 case CK_ARCConsumeObject:
John McCall31168b02011-06-15 23:02:42 +00001483 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
John McCall2d637d22011-09-10 06:18:15 +00001484 case CK_ARCReclaimReturnedObject: {
John McCall4db5c3c2011-07-07 06:58:02 +00001485 llvm::Value *value = Visit(E);
1486 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1487 return CGF.EmitObjCConsumeObject(E->getType(), value);
1488 }
John McCallff613032011-10-04 06:23:45 +00001489 case CK_ARCExtendBlockObject:
1490 return CGF.EmitARCExtendBlockObject(E);
John McCall31168b02011-06-15 23:02:42 +00001491
Douglas Gregored90df32012-02-22 05:02:47 +00001492 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmanec75fec2012-02-28 01:08:45 +00001493 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001494
John McCallc5e62b42010-11-13 09:02:35 +00001495 case CK_FloatingRealToComplex:
1496 case CK_FloatingComplexCast:
1497 case CK_IntegralRealToComplex:
1498 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00001499 case CK_IntegralComplexToFloatingComplex:
1500 case CK_FloatingComplexToIntegralComplex:
John McCalle3027922010-08-25 11:45:40 +00001501 case CK_ConstructorConversion:
John McCall3eba6e62010-11-16 06:21:14 +00001502 case CK_ToUnion:
1503 llvm_unreachable("scalar cast to non-scalar value");
John McCall34376a62010-12-04 03:47:34 +00001504
John McCallf3735e02010-12-01 04:43:34 +00001505 case CK_LValueToRValue:
1506 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCall34376a62010-12-04 03:47:34 +00001507 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCallf3735e02010-12-01 04:43:34 +00001508 return Visit(const_cast<Expr*>(E));
Eli Friedman0dfc6802009-11-27 02:07:44 +00001509
John McCalle3027922010-08-25 11:45:40 +00001510 case CK_IntegralToPointer: {
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001511 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbaread6824c2010-08-25 03:32:38 +00001512
Anders Carlsson094c4592009-10-18 18:12:03 +00001513 // First, convert to the correct width so that we control the kind of
1514 // extension.
Chris Lattner2192fe52011-07-18 04:24:23 +00001515 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001516 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
Anders Carlsson094c4592009-10-18 18:12:03 +00001517 llvm::Value* IntResult =
1518 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbaread6824c2010-08-25 03:32:38 +00001519
Anders Carlsson094c4592009-10-18 18:12:03 +00001520 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001521 }
Eli Friedman58368522011-06-25 02:58:47 +00001522 case CK_PointerToIntegral:
1523 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1524 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
Daniel Dunbaread6824c2010-08-25 03:32:38 +00001525
John McCalle3027922010-08-25 11:45:40 +00001526 case CK_ToVoid: {
John McCalla2342eb2010-12-05 02:00:02 +00001527 CGF.EmitIgnoredExpr(E);
Craig Topper8a13c412014-05-21 05:09:00 +00001528 return nullptr;
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001529 }
John McCalle3027922010-08-25 11:45:40 +00001530 case CK_VectorSplat: {
Chris Lattner2192fe52011-07-18 04:24:23 +00001531 llvm::Type *DstTy = ConvertType(DestTy);
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001532 Value *Elt = Visit(const_cast<Expr*>(E));
Craig Topper5b5935d2012-02-06 05:05:50 +00001533 Elt = EmitScalarConversion(Elt, E->getType(),
1534 DestTy->getAs<VectorType>()->getElementType());
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001535
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001536 // Splat the element across to all elements
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001537 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Alp Toker5f072d82014-04-19 23:55:49 +00001538 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001539 }
John McCall8cb679e2010-11-15 09:13:47 +00001540
John McCalle3027922010-08-25 11:45:40 +00001541 case CK_IntegralCast:
1542 case CK_IntegralToFloating:
1543 case CK_FloatingToIntegral:
1544 case CK_FloatingCast:
Eli Friedmane96f1d32009-11-27 04:41:50 +00001545 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
John McCall8cb679e2010-11-15 09:13:47 +00001546 case CK_IntegralToBoolean:
1547 return EmitIntToBoolConversion(Visit(E));
1548 case CK_PointerToBoolean:
1549 return EmitPointerToBoolConversion(Visit(E));
1550 case CK_FloatingToBoolean:
1551 return EmitFloatToBoolConversion(Visit(E));
John McCalle3027922010-08-25 11:45:40 +00001552 case CK_MemberPointerToBoolean: {
John McCall7a9aac22010-08-23 01:21:21 +00001553 llvm::Value *MemPtr = Visit(E);
1554 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1555 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlsson3df53bc2009-08-24 18:26:39 +00001556 }
John McCalld7646252010-11-14 08:17:51 +00001557
1558 case CK_FloatingComplexToReal:
1559 case CK_IntegralComplexToReal:
John McCall07bb1962010-11-16 10:08:07 +00001560 return CGF.EmitComplexExpr(E, false, true).first;
John McCalld7646252010-11-14 08:17:51 +00001561
1562 case CK_FloatingComplexToBoolean:
1563 case CK_IntegralComplexToBoolean: {
John McCall07bb1962010-11-16 10:08:07 +00001564 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCalld7646252010-11-14 08:17:51 +00001565
1566 // TODO: kill this function off, inline appropriate case here
1567 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1568 }
1569
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001570 case CK_ZeroToOCLEvent: {
Alp Tokerd4733632013-12-05 04:47:09 +00001571 assert(DestTy->isEventT() && "CK_ZeroToOCLEvent cast on non-event type");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001572 return llvm::Constant::getNullValue(ConvertType(DestTy));
1573 }
1574
John McCall7a9aac22010-08-23 01:21:21 +00001575 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001576
John McCall3eba6e62010-11-16 06:21:14 +00001577 llvm_unreachable("unknown scalar cast");
Chris Lattner2da04b32007-08-24 05:35:26 +00001578}
1579
Chris Lattner04a913b2007-08-31 22:09:40 +00001580Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCallce1de612011-01-26 04:00:11 +00001581 CodeGenFunction::StmtExprEvaluation eval(CGF);
Eli Friedman4871a462013-06-10 22:04:49 +00001582 llvm::Value *RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
1583 !E->getType()->isVoidType());
1584 if (!RetAlloca)
Craig Topper8a13c412014-05-21 05:09:00 +00001585 return nullptr;
Nick Lewycky2d84e842013-10-02 02:29:49 +00001586 return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
1587 E->getExprLoc());
Chris Lattner04a913b2007-08-31 22:09:40 +00001588}
1589
Chris Lattner2da04b32007-08-24 05:35:26 +00001590//===----------------------------------------------------------------------===//
1591// Unary Operators
1592//===----------------------------------------------------------------------===//
1593
Chris Lattner05dc78c2010-06-26 22:09:34 +00001594llvm::Value *ScalarExprEmitter::
Anton Yartsev85129b82011-02-07 02:17:30 +00001595EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1596 llvm::Value *InVal,
1597 llvm::Value *NextVal, bool IsInc) {
Richard Smith9c6890a2012-11-01 22:30:59 +00001598 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00001599 case LangOptions::SOB_Defined:
1600 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
Richard Smith3e056de2012-08-25 00:32:28 +00001601 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001602 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith3e056de2012-08-25 00:32:28 +00001603 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1604 // Fall through.
Anton Yartsev85129b82011-02-07 02:17:30 +00001605 case LangOptions::SOB_Trapping:
1606 BinOpInfo BinOp;
1607 BinOp.LHS = InVal;
1608 BinOp.RHS = NextVal;
1609 BinOp.Ty = E->getType();
1610 BinOp.Opcode = BO_Add;
Benjamin Kramerb15b97e2012-10-03 20:58:04 +00001611 BinOp.FPContractable = false;
Anton Yartsev85129b82011-02-07 02:17:30 +00001612 BinOp.E = E;
1613 return EmitOverflowCheckedBinOp(BinOp);
Anton Yartsev85129b82011-02-07 02:17:30 +00001614 }
David Blaikie83d382b2011-09-23 05:06:16 +00001615 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
Anton Yartsev85129b82011-02-07 02:17:30 +00001616}
1617
John McCalle3dc1702011-02-15 09:22:45 +00001618llvm::Value *
1619ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1620 bool isInc, bool isPre) {
Craig Toppera97d7e72013-07-26 06:16:11 +00001621
John McCalle3dc1702011-02-15 09:22:45 +00001622 QualType type = E->getSubExpr()->getType();
Craig Topper8a13c412014-05-21 05:09:00 +00001623 llvm::PHINode *atomicPHI = nullptr;
David Chisnallef78c302013-03-03 16:02:42 +00001624 llvm::Value *value;
1625 llvm::Value *input;
Anton Yartsev85129b82011-02-07 02:17:30 +00001626
John McCalle3dc1702011-02-15 09:22:45 +00001627 int amount = (isInc ? 1 : -1);
1628
David Chisnallfa35df62012-01-16 17:27:18 +00001629 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
David Chisnallef78c302013-03-03 16:02:42 +00001630 type = atomicTy->getValueType();
1631 if (isInc && type->isBooleanType()) {
1632 llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
1633 if (isPre) {
1634 Builder.Insert(new llvm::StoreInst(True,
1635 LV.getAddress(), LV.isVolatileQualified(),
1636 LV.getAlignment().getQuantity(),
1637 llvm::SequentiallyConsistent));
1638 return Builder.getTrue();
1639 }
1640 // For atomic bool increment, we just store true and return it for
1641 // preincrement, do an atomic swap with true for postincrement
1642 return Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg,
1643 LV.getAddress(), True, llvm::SequentiallyConsistent);
1644 }
1645 // Special case for atomic increment / decrement on integers, emit
1646 // atomicrmw instructions. We skip this if we want to be doing overflow
Craig Toppera97d7e72013-07-26 06:16:11 +00001647 // checking, and fall into the slow path with the atomic cmpxchg loop.
David Chisnallef78c302013-03-03 16:02:42 +00001648 if (!type->isBooleanType() && type->isIntegerType() &&
1649 !(type->isUnsignedIntegerType() &&
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001650 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
David Chisnallef78c302013-03-03 16:02:42 +00001651 CGF.getLangOpts().getSignedOverflowBehavior() !=
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001652 LangOptions::SOB_Trapping) {
David Chisnallef78c302013-03-03 16:02:42 +00001653 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
1654 llvm::AtomicRMWInst::Sub;
1655 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
1656 llvm::Instruction::Sub;
1657 llvm::Value *amt = CGF.EmitToMemory(
1658 llvm::ConstantInt::get(ConvertType(type), 1, true), type);
1659 llvm::Value *old = Builder.CreateAtomicRMW(aop,
1660 LV.getAddress(), amt, llvm::SequentiallyConsistent);
1661 return isPre ? Builder.CreateBinOp(op, old, amt) : old;
1662 }
Nick Lewycky2d84e842013-10-02 02:29:49 +00001663 value = EmitLoadOfLValue(LV, E->getExprLoc());
David Chisnallef78c302013-03-03 16:02:42 +00001664 input = value;
1665 // For every other atomic operation, we need to emit a load-op-cmpxchg loop
David Chisnallfa35df62012-01-16 17:27:18 +00001666 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1667 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
David Chisnallef78c302013-03-03 16:02:42 +00001668 value = CGF.EmitToMemory(value, type);
David Chisnallfa35df62012-01-16 17:27:18 +00001669 Builder.CreateBr(opBB);
1670 Builder.SetInsertPoint(opBB);
1671 atomicPHI = Builder.CreatePHI(value->getType(), 2);
1672 atomicPHI->addIncoming(value, startBB);
David Chisnallfa35df62012-01-16 17:27:18 +00001673 value = atomicPHI;
David Chisnallef78c302013-03-03 16:02:42 +00001674 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001675 value = EmitLoadOfLValue(LV, E->getExprLoc());
David Chisnallef78c302013-03-03 16:02:42 +00001676 input = value;
David Chisnallfa35df62012-01-16 17:27:18 +00001677 }
1678
John McCalle3dc1702011-02-15 09:22:45 +00001679 // Special case of integer increment that we have to check first: bool++.
1680 // Due to promotion rules, we get:
1681 // bool++ -> bool = bool + 1
1682 // -> bool = (int)bool + 1
1683 // -> bool = ((int)bool + 1 != 0)
1684 // An interesting aspect of this is that increment is always true.
1685 // Decrement does not have this property.
1686 if (isInc && type->isBooleanType()) {
1687 value = Builder.getTrue();
1688
1689 // Most common case by far: integer increment.
1690 } else if (type->isIntegerType()) {
1691
Michael Liao48f498f2012-08-28 16:55:13 +00001692 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
John McCalle3dc1702011-02-15 09:22:45 +00001693
Eli Friedman846ded22011-03-02 01:49:12 +00001694 // Note that signed integer inc/dec with width less than int can't
1695 // overflow because of promotion rules; we're just eliding a few steps here.
Richard Smith45d099b2014-07-07 05:36:14 +00001696 bool CanOverflow = value->getType()->getIntegerBitWidth() >=
1697 CGF.IntTy->getIntegerBitWidth();
1698 if (CanOverflow && type->isSignedIntegerOrEnumerationType()) {
John McCalle3dc1702011-02-15 09:22:45 +00001699 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
Richard Smith45d099b2014-07-07 05:36:14 +00001700 } else if (CanOverflow && type->isUnsignedIntegerType() &&
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001701 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
Will Dietz1897cb32012-11-27 15:01:55 +00001702 BinOpInfo BinOp;
1703 BinOp.LHS = value;
1704 BinOp.RHS = llvm::ConstantInt::get(value->getType(), 1, false);
1705 BinOp.Ty = E->getType();
1706 BinOp.Opcode = isInc ? BO_Add : BO_Sub;
1707 BinOp.FPContractable = false;
1708 BinOp.E = E;
1709 value = EmitOverflowCheckedBinOp(BinOp);
1710 } else
John McCalle3dc1702011-02-15 09:22:45 +00001711 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
Craig Toppera97d7e72013-07-26 06:16:11 +00001712
John McCalle3dc1702011-02-15 09:22:45 +00001713 // Next most common: pointer increment.
1714 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1715 QualType type = ptr->getPointeeType();
1716
1717 // VLA types don't have constant size.
John McCall77527a82011-06-25 01:32:37 +00001718 if (const VariableArrayType *vla
1719 = CGF.getContext().getAsVariableArrayType(type)) {
1720 llvm::Value *numElts = CGF.getVLASize(vla).first;
John McCall23c29fe2011-06-24 21:55:10 +00001721 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
Richard Smith9c6890a2012-11-01 22:30:59 +00001722 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall23c29fe2011-06-24 21:55:10 +00001723 value = Builder.CreateGEP(value, numElts, "vla.inc");
Chris Lattner2e72da942011-03-01 00:03:48 +00001724 else
John McCall23c29fe2011-06-24 21:55:10 +00001725 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
Craig Toppera97d7e72013-07-26 06:16:11 +00001726
John McCalle3dc1702011-02-15 09:22:45 +00001727 // Arithmetic on function pointers (!) is just +-1.
1728 } else if (type->isFunctionType()) {
Chris Lattner2531eb42011-04-19 22:55:03 +00001729 llvm::Value *amt = Builder.getInt32(amount);
John McCalle3dc1702011-02-15 09:22:45 +00001730
1731 value = CGF.EmitCastToVoidPtr(value);
Richard Smith9c6890a2012-11-01 22:30:59 +00001732 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00001733 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1734 else
1735 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
John McCalle3dc1702011-02-15 09:22:45 +00001736 value = Builder.CreateBitCast(value, input->getType());
1737
1738 // For everything else, we can just do a simple increment.
Anton Yartsev85129b82011-02-07 02:17:30 +00001739 } else {
Chris Lattner2531eb42011-04-19 22:55:03 +00001740 llvm::Value *amt = Builder.getInt32(amount);
Richard Smith9c6890a2012-11-01 22:30:59 +00001741 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00001742 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1743 else
1744 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
John McCalle3dc1702011-02-15 09:22:45 +00001745 }
1746
1747 // Vector increment/decrement.
1748 } else if (type->isVectorType()) {
1749 if (type->hasIntegerRepresentation()) {
1750 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1751
Eli Friedman409943e2011-05-06 18:04:18 +00001752 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
John McCalle3dc1702011-02-15 09:22:45 +00001753 } else {
1754 value = Builder.CreateFAdd(
1755 value,
1756 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev85129b82011-02-07 02:17:30 +00001757 isInc ? "inc" : "dec");
1758 }
Anton Yartsev85129b82011-02-07 02:17:30 +00001759
John McCalle3dc1702011-02-15 09:22:45 +00001760 // Floating point.
1761 } else if (type->isRealFloatingType()) {
Chris Lattner05dc78c2010-06-26 22:09:34 +00001762 // Add the inc/dec to the real part.
John McCalle3dc1702011-02-15 09:22:45 +00001763 llvm::Value *amt;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001764
Oliver Stannarded8ecc82014-08-27 16:31:57 +00001765 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
1766 !CGF.getContext().getLangOpts().HalfArgsAndReturns) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001767 // Another special case: half FP increment should be done via float
Tim Northover6dbcbac2014-07-17 10:51:31 +00001768 value = Builder.CreateCall(
1769 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
1770 CGF.CGM.FloatTy),
1771 input);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001772 }
1773
John McCalle3dc1702011-02-15 09:22:45 +00001774 if (value->getType()->isFloatTy())
1775 amt = llvm::ConstantFP::get(VMContext,
1776 llvm::APFloat(static_cast<float>(amount)));
1777 else if (value->getType()->isDoubleTy())
1778 amt = llvm::ConstantFP::get(VMContext,
1779 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner05dc78c2010-06-26 22:09:34 +00001780 else {
John McCalle3dc1702011-02-15 09:22:45 +00001781 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner05dc78c2010-06-26 22:09:34 +00001782 bool ignored;
John McCallc8e01702013-04-16 22:48:15 +00001783 F.convert(CGF.getTarget().getLongDoubleFormat(),
1784 llvm::APFloat::rmTowardZero, &ignored);
John McCalle3dc1702011-02-15 09:22:45 +00001785 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner05dc78c2010-06-26 22:09:34 +00001786 }
John McCalle3dc1702011-02-15 09:22:45 +00001787 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1788
Oliver Stannarded8ecc82014-08-27 16:31:57 +00001789 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
1790 !CGF.getContext().getLangOpts().HalfArgsAndReturns)
Tim Northover6dbcbac2014-07-17 10:51:31 +00001791 value = Builder.CreateCall(
1792 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
1793 CGF.CGM.FloatTy),
1794 value);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001795
John McCalle3dc1702011-02-15 09:22:45 +00001796 // Objective-C pointer types.
1797 } else {
1798 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1799 value = CGF.EmitCastToVoidPtr(value);
1800
1801 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1802 if (!isInc) size = -size;
1803 llvm::Value *sizeValue =
1804 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1805
Richard Smith9c6890a2012-11-01 22:30:59 +00001806 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00001807 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1808 else
1809 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
John McCalle3dc1702011-02-15 09:22:45 +00001810 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner05dc78c2010-06-26 22:09:34 +00001811 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001812
David Chisnallfa35df62012-01-16 17:27:18 +00001813 if (atomicPHI) {
1814 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1815 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001816 auto Pair = CGF.EmitAtomicCompareExchange(
1817 LV, RValue::get(atomicPHI), RValue::get(CGF.EmitToMemory(value, type)),
1818 E->getExprLoc());
1819 llvm::Value *old = Pair.first.getScalarVal();
1820 llvm::Value *success = Pair.second.getScalarVal();
David Chisnallfa35df62012-01-16 17:27:18 +00001821 atomicPHI->addIncoming(old, opBB);
David Chisnallfa35df62012-01-16 17:27:18 +00001822 Builder.CreateCondBr(success, contBB, opBB);
1823 Builder.SetInsertPoint(contBB);
1824 return isPre ? value : input;
1825 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001826
Chris Lattner05dc78c2010-06-26 22:09:34 +00001827 // Store the updated result through the lvalue.
1828 if (LV.isBitField())
John McCall55e1fbc2011-06-25 02:11:03 +00001829 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
Chris Lattner05dc78c2010-06-26 22:09:34 +00001830 else
John McCall55e1fbc2011-06-25 02:11:03 +00001831 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001832
Chris Lattner05dc78c2010-06-26 22:09:34 +00001833 // If this is a postinc, return the value read from memory, otherwise use the
1834 // updated value.
John McCalle3dc1702011-02-15 09:22:45 +00001835 return isPre ? value : input;
Chris Lattner05dc78c2010-06-26 22:09:34 +00001836}
1837
1838
1839
Chris Lattner2da04b32007-08-24 05:35:26 +00001840Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00001841 TestAndClearIgnoreResultAssign();
Chris Lattner0bf27622010-06-26 21:48:21 +00001842 // Emit unary minus with EmitSub so we handle overflow cases etc.
1843 BinOpInfo BinOp;
Chris Lattnerc1028f62010-06-28 17:12:37 +00001844 BinOp.RHS = Visit(E->getSubExpr());
Craig Toppera97d7e72013-07-26 06:16:11 +00001845
Chris Lattnerc1028f62010-06-28 17:12:37 +00001846 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1847 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001848 else
Chris Lattnerc1028f62010-06-28 17:12:37 +00001849 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner0bf27622010-06-26 21:48:21 +00001850 BinOp.Ty = E->getType();
John McCalle3027922010-08-25 11:45:40 +00001851 BinOp.Opcode = BO_Sub;
Benjamin Kramerb15b97e2012-10-03 20:58:04 +00001852 BinOp.FPContractable = false;
Chris Lattner0bf27622010-06-26 21:48:21 +00001853 BinOp.E = E;
1854 return EmitSub(BinOp);
Chris Lattner2da04b32007-08-24 05:35:26 +00001855}
1856
1857Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00001858 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +00001859 Value *Op = Visit(E->getSubExpr());
1860 return Builder.CreateNot(Op, "neg");
1861}
1862
1863Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00001864 // Perform vector logical not on comparison with zero vector.
1865 if (E->getType()->isExtVectorType()) {
1866 Value *Oper = Visit(E->getSubExpr());
1867 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
Joey Gouly7d00f002013-02-21 11:49:56 +00001868 Value *Result;
1869 if (Oper->getType()->isFPOrFPVectorTy())
1870 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
1871 else
1872 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
Tanya Lattner20248222012-01-16 21:02:28 +00001873 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1874 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001875
Chris Lattner2da04b32007-08-24 05:35:26 +00001876 // Compare operand to zero.
1877 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00001878
Chris Lattner2da04b32007-08-24 05:35:26 +00001879 // Invert value.
1880 // TODO: Could dynamically modify easy computations here. For example, if
1881 // the operand is an icmp ne, turn into icmp eq.
1882 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stump4a3999f2009-09-09 13:00:44 +00001883
Anders Carlsson775640d2009-05-19 18:44:53 +00001884 // ZExt result to the expr type.
1885 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00001886}
1887
Eli Friedmand7c72322010-08-05 09:58:49 +00001888Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1889 // Try folding the offsetof to a constant.
Richard Smith5fab0c92011-12-28 19:48:30 +00001890 llvm::APSInt Value;
1891 if (E->EvaluateAsInt(Value, CGF.getContext()))
1892 return Builder.getInt(Value);
Eli Friedmand7c72322010-08-05 09:58:49 +00001893
1894 // Loop over the components of the offsetof to compute the value.
1895 unsigned n = E->getNumComponents();
Chris Lattner2192fe52011-07-18 04:24:23 +00001896 llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedmand7c72322010-08-05 09:58:49 +00001897 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1898 QualType CurrentType = E->getTypeSourceInfo()->getType();
1899 for (unsigned i = 0; i != n; ++i) {
1900 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Craig Topper8a13c412014-05-21 05:09:00 +00001901 llvm::Value *Offset = nullptr;
Eli Friedmand7c72322010-08-05 09:58:49 +00001902 switch (ON.getKind()) {
1903 case OffsetOfExpr::OffsetOfNode::Array: {
1904 // Compute the index
1905 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1906 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001907 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Eli Friedmand7c72322010-08-05 09:58:49 +00001908 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1909
1910 // Save the element type
1911 CurrentType =
1912 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1913
1914 // Compute the element size
1915 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1916 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1917
1918 // Multiply out to compute the result
1919 Offset = Builder.CreateMul(Idx, ElemSize);
1920 break;
1921 }
1922
1923 case OffsetOfExpr::OffsetOfNode::Field: {
1924 FieldDecl *MemberDecl = ON.getField();
1925 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1926 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1927
1928 // Compute the index of the field in its parent.
1929 unsigned i = 0;
1930 // FIXME: It would be nice if we didn't have to loop here!
1931 for (RecordDecl::field_iterator Field = RD->field_begin(),
1932 FieldEnd = RD->field_end();
David Blaikie2d7c57e2012-04-30 02:36:29 +00001933 Field != FieldEnd; ++Field, ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00001934 if (*Field == MemberDecl)
Eli Friedmand7c72322010-08-05 09:58:49 +00001935 break;
1936 }
1937 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1938
1939 // Compute the offset to the field
1940 int64_t OffsetInt = RL.getFieldOffset(i) /
1941 CGF.getContext().getCharWidth();
1942 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1943
1944 // Save the element type.
1945 CurrentType = MemberDecl->getType();
1946 break;
1947 }
Eli Friedman165301d2010-08-06 16:37:05 +00001948
Eli Friedmand7c72322010-08-05 09:58:49 +00001949 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedmane83d2b762010-08-06 01:17:25 +00001950 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman165301d2010-08-06 16:37:05 +00001951
Eli Friedmand7c72322010-08-05 09:58:49 +00001952 case OffsetOfExpr::OffsetOfNode::Base: {
1953 if (ON.getBase()->isVirtual()) {
1954 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1955 continue;
1956 }
1957
1958 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1959 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1960
1961 // Save the element type.
1962 CurrentType = ON.getBase()->getType();
Craig Toppera97d7e72013-07-26 06:16:11 +00001963
Eli Friedmand7c72322010-08-05 09:58:49 +00001964 // Compute the offset to the base.
1965 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1966 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001967 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
1968 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
Eli Friedmand7c72322010-08-05 09:58:49 +00001969 break;
1970 }
1971 }
1972 Result = Builder.CreateAdd(Result, Offset);
1973 }
1974 return Result;
Douglas Gregor882211c2010-04-28 22:16:22 +00001975}
1976
Peter Collingbournee190dee2011-03-11 19:24:49 +00001977/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl6f282892008-11-11 17:56:53 +00001978/// argument of the sizeof expression as an integer.
1979Value *
Peter Collingbournee190dee2011-03-11 19:24:49 +00001980ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1981 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl6f282892008-11-11 17:56:53 +00001982 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournee190dee2011-03-11 19:24:49 +00001983 if (E->getKind() == UETT_SizeOf) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001984 if (const VariableArrayType *VAT =
Eli Friedman2aa38fe2009-01-24 22:19:05 +00001985 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1986 if (E->isArgumentType()) {
1987 // sizeof(type) - make sure to emit the VLA size.
John McCall23c29fe2011-06-24 21:55:10 +00001988 CGF.EmitVariablyModifiedType(TypeToSize);
Eli Friedman3253e182009-04-20 03:21:44 +00001989 } else {
1990 // C99 6.5.3.4p2: If the argument is an expression of type
1991 // VLA, it is evaluated.
John McCalla2342eb2010-12-05 02:00:02 +00001992 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedman2aa38fe2009-01-24 22:19:05 +00001993 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001994
John McCall23c29fe2011-06-24 21:55:10 +00001995 QualType eltType;
1996 llvm::Value *numElts;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001997 std::tie(numElts, eltType) = CGF.getVLASize(VAT);
John McCall23c29fe2011-06-24 21:55:10 +00001998
1999 llvm::Value *size = numElts;
2000
2001 // Scale the number of non-VLA elements by the non-VLA element size.
2002 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
2003 if (!eltSize.isOne())
2004 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
2005
2006 return size;
Anders Carlsson76dbc042008-12-21 03:33:21 +00002007 }
Anders Carlsson30032882008-12-12 07:38:43 +00002008 }
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002009
Mike Stump4a3999f2009-09-09 13:00:44 +00002010 // If this isn't sizeof(vla), the result must be constant; use the constant
2011 // folding logic so we don't have to duplicate it here.
Richard Smith5fab0c92011-12-28 19:48:30 +00002012 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
Chris Lattner2da04b32007-08-24 05:35:26 +00002013}
2014
Chris Lattner9f0ad962007-08-24 21:20:17 +00002015Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
2016 Expr *Op = E->getSubExpr();
John McCall07bb1962010-11-16 10:08:07 +00002017 if (Op->getType()->isAnyComplexType()) {
2018 // If it's an l-value, load through the appropriate subobject l-value.
2019 // Note that we have to ask E because Op might be an l-value that
2020 // this won't work for, e.g. an Obj-C property.
John McCall086a4642010-11-24 05:12:34 +00002021 if (E->isGLValue())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002022 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2023 E->getExprLoc()).getScalarVal();
John McCall07bb1962010-11-16 10:08:07 +00002024
2025 // Otherwise, calculate and project.
2026 return CGF.EmitComplexExpr(Op, false, true).first;
2027 }
2028
Chris Lattner9f0ad962007-08-24 21:20:17 +00002029 return Visit(Op);
2030}
John McCall07bb1962010-11-16 10:08:07 +00002031
Chris Lattner9f0ad962007-08-24 21:20:17 +00002032Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
2033 Expr *Op = E->getSubExpr();
John McCall07bb1962010-11-16 10:08:07 +00002034 if (Op->getType()->isAnyComplexType()) {
2035 // If it's an l-value, load through the appropriate subobject l-value.
2036 // Note that we have to ask E because Op might be an l-value that
2037 // this won't work for, e.g. an Obj-C property.
John McCall086a4642010-11-24 05:12:34 +00002038 if (Op->isGLValue())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002039 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2040 E->getExprLoc()).getScalarVal();
John McCall07bb1962010-11-16 10:08:07 +00002041
2042 // Otherwise, calculate and project.
2043 return CGF.EmitComplexExpr(Op, true, false).second;
2044 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002045
Mike Stumpdf0fe272009-05-29 15:46:01 +00002046 // __imag on a scalar returns zero. Emit the subexpr to ensure side
2047 // effects are evaluated, but not the actual value.
Richard Smith0b6b8e42012-02-18 20:53:32 +00002048 if (Op->isGLValue())
2049 CGF.EmitLValue(Op);
2050 else
2051 CGF.EmitScalarExpr(Op, true);
Owen Anderson0b75f232009-07-31 20:28:54 +00002052 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner9f0ad962007-08-24 21:20:17 +00002053}
2054
Chris Lattner2da04b32007-08-24 05:35:26 +00002055//===----------------------------------------------------------------------===//
2056// Binary Operators
2057//===----------------------------------------------------------------------===//
2058
2059BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002060 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +00002061 BinOpInfo Result;
2062 Result.LHS = Visit(E->getLHS());
2063 Result.RHS = Visit(E->getRHS());
Chris Lattner3d966d62007-08-24 21:00:35 +00002064 Result.Ty = E->getType();
Chris Lattner0bf27622010-06-26 21:48:21 +00002065 Result.Opcode = E->getOpcode();
Lang Hames5de91cc2012-10-02 04:45:10 +00002066 Result.FPContractable = E->isFPContractable();
Chris Lattner2da04b32007-08-24 05:35:26 +00002067 Result.E = E;
2068 return Result;
2069}
2070
Douglas Gregor914af212010-04-23 04:16:32 +00002071LValue ScalarExprEmitter::EmitCompoundAssignLValue(
2072 const CompoundAssignOperator *E,
2073 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002074 Value *&Result) {
Benjamin Kramerd20ef752009-12-25 15:43:36 +00002075 QualType LHSTy = E->getLHS()->getType();
Chris Lattner3d966d62007-08-24 21:00:35 +00002076 BinOpInfo OpInfo;
Craig Toppera97d7e72013-07-26 06:16:11 +00002077
Eli Friedmanf0450072013-06-12 01:40:06 +00002078 if (E->getComputationResultType()->isAnyComplexType())
Richard Smith527473d2015-02-12 21:23:20 +00002079 return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
Craig Toppera97d7e72013-07-26 06:16:11 +00002080
Mike Stumpc63428b2009-05-22 19:07:20 +00002081 // Emit the RHS first. __block variables need to have the rhs evaluated
2082 // first, plus this should improve codegen a little.
2083 OpInfo.RHS = Visit(E->getRHS());
2084 OpInfo.Ty = E->getComputationResultType();
Chris Lattner0bf27622010-06-26 21:48:21 +00002085 OpInfo.Opcode = E->getOpcode();
Benjamin Kramerb15b97e2012-10-03 20:58:04 +00002086 OpInfo.FPContractable = false;
Mike Stumpc63428b2009-05-22 19:07:20 +00002087 OpInfo.E = E;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00002088 // Load/convert the LHS.
Richard Smith4d1458e2012-09-08 02:08:36 +00002089 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
David Chisnallfa35df62012-01-16 17:27:18 +00002090
Craig Topper8a13c412014-05-21 05:09:00 +00002091 llvm::PHINode *atomicPHI = nullptr;
David Chisnallef78c302013-03-03 16:02:42 +00002092 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
2093 QualType type = atomicTy->getValueType();
2094 if (!type->isBooleanType() && type->isIntegerType() &&
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002095 !(type->isUnsignedIntegerType() &&
2096 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2097 CGF.getLangOpts().getSignedOverflowBehavior() !=
2098 LangOptions::SOB_Trapping) {
David Chisnallef78c302013-03-03 16:02:42 +00002099 llvm::AtomicRMWInst::BinOp aop = llvm::AtomicRMWInst::BAD_BINOP;
2100 switch (OpInfo.Opcode) {
2101 // We don't have atomicrmw operands for *, %, /, <<, >>
2102 case BO_MulAssign: case BO_DivAssign:
2103 case BO_RemAssign:
2104 case BO_ShlAssign:
2105 case BO_ShrAssign:
2106 break;
2107 case BO_AddAssign:
2108 aop = llvm::AtomicRMWInst::Add;
2109 break;
2110 case BO_SubAssign:
2111 aop = llvm::AtomicRMWInst::Sub;
2112 break;
2113 case BO_AndAssign:
2114 aop = llvm::AtomicRMWInst::And;
2115 break;
2116 case BO_XorAssign:
2117 aop = llvm::AtomicRMWInst::Xor;
2118 break;
2119 case BO_OrAssign:
2120 aop = llvm::AtomicRMWInst::Or;
2121 break;
2122 default:
2123 llvm_unreachable("Invalid compound assignment type");
2124 }
2125 if (aop != llvm::AtomicRMWInst::BAD_BINOP) {
2126 llvm::Value *amt = CGF.EmitToMemory(EmitScalarConversion(OpInfo.RHS,
2127 E->getRHS()->getType(), LHSTy), LHSTy);
2128 Builder.CreateAtomicRMW(aop, LHSLV.getAddress(), amt,
2129 llvm::SequentiallyConsistent);
2130 return LHSLV;
2131 }
2132 }
David Chisnallfa35df62012-01-16 17:27:18 +00002133 // FIXME: For floating point types, we should be saving and restoring the
2134 // floating point environment in the loop.
2135 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2136 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
Nick Lewycky2d84e842013-10-02 02:29:49 +00002137 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
David Chisnallef78c302013-03-03 16:02:42 +00002138 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
David Chisnallfa35df62012-01-16 17:27:18 +00002139 Builder.CreateBr(opBB);
2140 Builder.SetInsertPoint(opBB);
2141 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
2142 atomicPHI->addIncoming(OpInfo.LHS, startBB);
David Chisnallfa35df62012-01-16 17:27:18 +00002143 OpInfo.LHS = atomicPHI;
2144 }
David Chisnallef78c302013-03-03 16:02:42 +00002145 else
Nick Lewycky2d84e842013-10-02 02:29:49 +00002146 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002147
2148 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
2149 E->getComputationLHSType());
2150
Chris Lattner3d966d62007-08-24 21:00:35 +00002151 // Expand the binary operator.
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002152 Result = (this->*Func)(OpInfo);
Craig Toppera97d7e72013-07-26 06:16:11 +00002153
Daniel Dunbarbfb1cd72008-08-06 02:00:38 +00002154 // Convert the result back to the LHS type.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00002155 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
David Chisnallfa35df62012-01-16 17:27:18 +00002156
2157 if (atomicPHI) {
2158 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
2159 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
Alexey Bataev452d8e12014-12-15 05:25:25 +00002160 auto Pair = CGF.EmitAtomicCompareExchange(
2161 LHSLV, RValue::get(atomicPHI),
2162 RValue::get(CGF.EmitToMemory(Result, LHSTy)), E->getExprLoc());
2163 llvm::Value *old = Pair.first.getScalarVal();
2164 llvm::Value *success = Pair.second.getScalarVal();
David Chisnallfa35df62012-01-16 17:27:18 +00002165 atomicPHI->addIncoming(old, opBB);
David Chisnallfa35df62012-01-16 17:27:18 +00002166 Builder.CreateCondBr(success, contBB, opBB);
2167 Builder.SetInsertPoint(contBB);
2168 return LHSLV;
2169 }
Craig Toppera97d7e72013-07-26 06:16:11 +00002170
Mike Stump4a3999f2009-09-09 13:00:44 +00002171 // Store the result value into the LHS lvalue. Bit-fields are handled
2172 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
2173 // 'An assignment expression has the value of the left operand after the
2174 // assignment...'.
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002175 if (LHSLV.isBitField())
John McCall55e1fbc2011-06-25 02:11:03 +00002176 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002177 else
John McCall55e1fbc2011-06-25 02:11:03 +00002178 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002179
Douglas Gregor914af212010-04-23 04:16:32 +00002180 return LHSLV;
2181}
2182
2183Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
2184 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
2185 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002186 Value *RHS;
2187 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
2188
2189 // If the result is clearly ignored, return now.
Mike Stumpdf0fe272009-05-29 15:46:01 +00002190 if (Ignore)
Craig Topper8a13c412014-05-21 05:09:00 +00002191 return nullptr;
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002192
John McCall07bb1962010-11-16 10:08:07 +00002193 // The result of an assignment in C is the assigned r-value.
Richard Smith9c6890a2012-11-01 22:30:59 +00002194 if (!CGF.getLangOpts().CPlusPlus)
John McCall07bb1962010-11-16 10:08:07 +00002195 return RHS;
2196
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002197 // If the lvalue is non-volatile, return the computed value of the assignment.
2198 if (!LHS.isVolatileQualified())
2199 return RHS;
2200
2201 // Otherwise, reload the value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002202 return EmitLoadOfLValue(LHS, E->getExprLoc());
Chris Lattner3d966d62007-08-24 21:00:35 +00002203}
2204
Chris Lattner8ee6a412010-09-11 21:47:09 +00002205void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
Richard Smith4d1458e2012-09-08 02:08:36 +00002206 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002207 SmallVector<std::pair<llvm::Value *, SanitizerKind>, 2> Checks;
Chris Lattner8ee6a412010-09-11 21:47:09 +00002208
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002209 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002210 Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
2211 SanitizerKind::IntegerDivideByZero));
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002212 }
Richard Smithc86a1142012-11-06 02:30:30 +00002213
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002214 if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
Richard Smithc86a1142012-11-06 02:30:30 +00002215 Ops.Ty->hasSignedIntegerRepresentation()) {
2216 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
2217
Chris Lattner8ee6a412010-09-11 21:47:09 +00002218 llvm::Value *IntMin =
Chris Lattner2531eb42011-04-19 22:55:03 +00002219 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
Chris Lattner8ee6a412010-09-11 21:47:09 +00002220 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
2221
Richard Smith4d1458e2012-09-08 02:08:36 +00002222 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
2223 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002224 llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
2225 Checks.push_back(
2226 std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
Chris Lattner8ee6a412010-09-11 21:47:09 +00002227 }
Richard Smithc86a1142012-11-06 02:30:30 +00002228
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002229 if (Checks.size() > 0)
2230 EmitBinOpCheck(Checks, Ops);
Chris Lattner8ee6a412010-09-11 21:47:09 +00002231}
Chris Lattner3d966d62007-08-24 21:00:35 +00002232
Chris Lattner2da04b32007-08-24 05:35:26 +00002233Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002234 {
2235 CodeGenFunction::SanitizerScope SanScope(&CGF);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002236 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
2237 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
Alexey Samsonov24cad992014-07-17 18:46:27 +00002238 Ops.Ty->isIntegerType()) {
2239 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2240 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002241 } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
Alexey Samsonov24cad992014-07-17 18:46:27 +00002242 Ops.Ty->isRealFloatingType()) {
2243 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002244 llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
2245 EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
2246 Ops);
Alexey Samsonov24cad992014-07-17 18:46:27 +00002247 }
Chris Lattner8ee6a412010-09-11 21:47:09 +00002248 }
Will Dietz1897cb32012-11-27 15:01:55 +00002249
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00002250 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
2251 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Richard Smith9c6890a2012-11-01 22:30:59 +00002252 if (CGF.getLangOpts().OpenCL) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00002253 // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
2254 llvm::Type *ValTy = Val->getType();
2255 if (ValTy->isFloatTy() ||
2256 (isa<llvm::VectorType>(ValTy) &&
2257 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
Duncan Sandse81111c2012-04-10 08:23:07 +00002258 CGF.SetFPAccuracy(Val, 2.5);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00002259 }
2260 return Val;
2261 }
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002262 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00002263 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
2264 else
2265 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
2266}
2267
2268Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
2269 // Rem in C can't be a floating point type: C99 6.5.5p2.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002270 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002271 CodeGenFunction::SanitizerScope SanScope(&CGF);
Chris Lattner8ee6a412010-09-11 21:47:09 +00002272 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2273
Will Dietz1897cb32012-11-27 15:01:55 +00002274 if (Ops.Ty->isIntegerType())
Chris Lattner8ee6a412010-09-11 21:47:09 +00002275 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
2276 }
2277
Eli Friedman493c34a2011-04-10 04:44:11 +00002278 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00002279 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
2280 else
2281 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
2282}
2283
Mike Stump0c61b732009-04-01 20:28:16 +00002284Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
2285 unsigned IID;
2286 unsigned OpID = 0;
Mike Stump40968592009-04-02 01:03:55 +00002287
Will Dietz1897cb32012-11-27 15:01:55 +00002288 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
Chris Lattner0bf27622010-06-26 21:48:21 +00002289 switch (Ops.Opcode) {
John McCalle3027922010-08-25 11:45:40 +00002290 case BO_Add:
2291 case BO_AddAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00002292 OpID = 1;
Will Dietz1897cb32012-11-27 15:01:55 +00002293 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
2294 llvm::Intrinsic::uadd_with_overflow;
Mike Stumpd3e38852009-04-02 18:15:54 +00002295 break;
John McCalle3027922010-08-25 11:45:40 +00002296 case BO_Sub:
2297 case BO_SubAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00002298 OpID = 2;
Will Dietz1897cb32012-11-27 15:01:55 +00002299 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
2300 llvm::Intrinsic::usub_with_overflow;
Mike Stumpd3e38852009-04-02 18:15:54 +00002301 break;
John McCalle3027922010-08-25 11:45:40 +00002302 case BO_Mul:
2303 case BO_MulAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00002304 OpID = 3;
Will Dietz1897cb32012-11-27 15:01:55 +00002305 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
2306 llvm::Intrinsic::umul_with_overflow;
Mike Stumpd3e38852009-04-02 18:15:54 +00002307 break;
2308 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002309 llvm_unreachable("Unsupported operation for overflow detection");
Mike Stump0c61b732009-04-01 20:28:16 +00002310 }
Mike Stumpd3e38852009-04-02 18:15:54 +00002311 OpID <<= 1;
Will Dietz1897cb32012-11-27 15:01:55 +00002312 if (isSigned)
2313 OpID |= 1;
Mike Stumpd3e38852009-04-02 18:15:54 +00002314
Chris Lattnera5f58b02011-07-09 17:41:47 +00002315 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
Mike Stump0c61b732009-04-01 20:28:16 +00002316
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00002317 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
Mike Stump0c61b732009-04-01 20:28:16 +00002318
2319 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
2320 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
2321 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
2322
Richard Smith4d1458e2012-09-08 02:08:36 +00002323 // Handle overflow with llvm.trap if no custom handler has been specified.
2324 const std::string *handlerName =
Richard Smith9c6890a2012-11-01 22:30:59 +00002325 &CGF.getLangOpts().OverflowHandler;
Richard Smith4d1458e2012-09-08 02:08:36 +00002326 if (handlerName->empty()) {
Richard Smithb1b0ab42012-11-05 22:21:05 +00002327 // If the signed-integer-overflow sanitizer is enabled, emit a call to its
Richard Smithde670682012-11-01 22:15:34 +00002328 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002329 if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002330 CodeGenFunction::SanitizerScope SanScope(&CGF);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002331 llvm::Value *NotOverflow = Builder.CreateNot(overflow);
2332 SanitizerKind Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
2333 : SanitizerKind::UnsignedIntegerOverflow;
2334 EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
Alexey Samsonov24cad992014-07-17 18:46:27 +00002335 } else
Chad Rosierae229d52013-01-29 23:31:22 +00002336 CGF.EmitTrapCheck(Builder.CreateNot(overflow));
Richard Smith4d1458e2012-09-08 02:08:36 +00002337 return result;
2338 }
2339
Mike Stump0c61b732009-04-01 20:28:16 +00002340 // Branch in case of overflow.
David Chisnalldd84ef12010-09-17 18:29:54 +00002341 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Bill Wendlinge367f382011-07-07 21:13:10 +00002342 llvm::Function::iterator insertPt = initialBB;
2343 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
Benjamin Kramer167e9992014-03-02 12:20:24 +00002344 std::next(insertPt));
Chris Lattner8139c982010-08-07 00:20:46 +00002345 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Mike Stump0c61b732009-04-01 20:28:16 +00002346
2347 Builder.CreateCondBr(overflow, overflowBB, continueBB);
2348
David Chisnalldd84ef12010-09-17 18:29:54 +00002349 // If an overflow handler is set, then we want to call it and then use its
2350 // result, if it returns.
2351 Builder.SetInsertPoint(overflowBB);
2352
2353 // Get the overflow handler.
Chris Lattnerece04092012-02-07 00:39:47 +00002354 llvm::Type *Int8Ty = CGF.Int8Ty;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002355 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
David Chisnalldd84ef12010-09-17 18:29:54 +00002356 llvm::FunctionType *handlerTy =
2357 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
2358 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
2359
2360 // Sign extend the args to 64-bit, so that we can use the same handler for
2361 // all types of overflow.
2362 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
2363 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
2364
2365 // Call the handler with the two arguments, the operation, and the size of
2366 // the result.
John McCall882987f2013-02-28 19:01:20 +00002367 llvm::Value *handlerArgs[] = {
2368 lhs,
2369 rhs,
2370 Builder.getInt8(OpID),
2371 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
2372 };
2373 llvm::Value *handlerResult =
2374 CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
David Chisnalldd84ef12010-09-17 18:29:54 +00002375
2376 // Truncate the result back to the desired size.
2377 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
2378 Builder.CreateBr(continueBB);
2379
Mike Stump0c61b732009-04-01 20:28:16 +00002380 Builder.SetInsertPoint(continueBB);
Jay Foad20c0f022011-03-30 11:28:58 +00002381 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
David Chisnalldd84ef12010-09-17 18:29:54 +00002382 phi->addIncoming(result, initialBB);
2383 phi->addIncoming(handlerResult, overflowBB);
2384
2385 return phi;
Mike Stump0c61b732009-04-01 20:28:16 +00002386}
Chris Lattner2da04b32007-08-24 05:35:26 +00002387
John McCall77527a82011-06-25 01:32:37 +00002388/// Emit pointer + index arithmetic.
2389static Value *emitPointerArithmetic(CodeGenFunction &CGF,
2390 const BinOpInfo &op,
2391 bool isSubtraction) {
2392 // Must have binary (not unary) expr here. Unary pointer
2393 // increment/decrement doesn't use this path.
2394 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
Craig Toppera97d7e72013-07-26 06:16:11 +00002395
John McCall77527a82011-06-25 01:32:37 +00002396 Value *pointer = op.LHS;
2397 Expr *pointerOperand = expr->getLHS();
2398 Value *index = op.RHS;
2399 Expr *indexOperand = expr->getRHS();
2400
2401 // In a subtraction, the LHS is always the pointer.
2402 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
2403 std::swap(pointer, index);
2404 std::swap(pointerOperand, indexOperand);
2405 }
2406
2407 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
2408 if (width != CGF.PointerWidthInBits) {
2409 // Zero-extend or sign-extend the pointer value according to
2410 // whether the index is signed or not.
2411 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
2412 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
2413 "idx.ext");
2414 }
2415
2416 // If this is subtraction, negate the index.
2417 if (isSubtraction)
2418 index = CGF.Builder.CreateNeg(index, "idx.neg");
2419
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002420 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00002421 CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
2422 /*Accessed*/ false);
2423
John McCall77527a82011-06-25 01:32:37 +00002424 const PointerType *pointerType
2425 = pointerOperand->getType()->getAs<PointerType>();
2426 if (!pointerType) {
2427 QualType objectType = pointerOperand->getType()
2428 ->castAs<ObjCObjectPointerType>()
2429 ->getPointeeType();
2430 llvm::Value *objectSize
2431 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
2432
2433 index = CGF.Builder.CreateMul(index, objectSize);
2434
2435 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2436 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2437 return CGF.Builder.CreateBitCast(result, pointer->getType());
2438 }
2439
2440 QualType elementType = pointerType->getPointeeType();
2441 if (const VariableArrayType *vla
2442 = CGF.getContext().getAsVariableArrayType(elementType)) {
2443 // The element count here is the total number of non-VLA elements.
2444 llvm::Value *numElements = CGF.getVLASize(vla).first;
2445
2446 // Effectively, the multiply by the VLA size is part of the GEP.
2447 // GEP indexes are signed, and scaling an index isn't permitted to
2448 // signed-overflow, so we use the same semantics for our explicit
2449 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002450 if (CGF.getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00002451 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
2452 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2453 } else {
2454 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
2455 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattner51924e512010-06-26 21:25:03 +00002456 }
John McCall77527a82011-06-25 01:32:37 +00002457 return pointer;
Mike Stump4a3999f2009-09-09 13:00:44 +00002458 }
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002459
Mike Stump4a3999f2009-09-09 13:00:44 +00002460 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
2461 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
2462 // future proof.
John McCall77527a82011-06-25 01:32:37 +00002463 if (elementType->isVoidType() || elementType->isFunctionType()) {
2464 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2465 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2466 return CGF.Builder.CreateBitCast(result, pointer->getType());
Mike Stump4a3999f2009-09-09 13:00:44 +00002467 }
2468
David Blaikiebbafb8a2012-03-11 07:00:24 +00002469 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall77527a82011-06-25 01:32:37 +00002470 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2471
2472 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattner2da04b32007-08-24 05:35:26 +00002473}
2474
Lang Hames5de91cc2012-10-02 04:45:10 +00002475// Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
2476// Addend. Use negMul and negAdd to negate the first operand of the Mul or
2477// the add operand respectively. This allows fmuladd to represent a*b-c, or
2478// c-a*b. Patterns in LLVM should catch the negated forms and translate them to
2479// efficient operations.
2480static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
2481 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2482 bool negMul, bool negAdd) {
2483 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
Craig Toppera97d7e72013-07-26 06:16:11 +00002484
Lang Hames5de91cc2012-10-02 04:45:10 +00002485 Value *MulOp0 = MulOp->getOperand(0);
2486 Value *MulOp1 = MulOp->getOperand(1);
2487 if (negMul) {
2488 MulOp0 =
2489 Builder.CreateFSub(
2490 llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
2491 "neg");
2492 } else if (negAdd) {
2493 Addend =
2494 Builder.CreateFSub(
2495 llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
2496 "neg");
2497 }
2498
2499 Value *FMulAdd =
2500 Builder.CreateCall3(
2501 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
2502 MulOp0, MulOp1, Addend);
2503 MulOp->eraseFromParent();
2504
2505 return FMulAdd;
2506}
2507
2508// Check whether it would be legal to emit an fmuladd intrinsic call to
2509// represent op and if so, build the fmuladd.
2510//
2511// Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
2512// Does NOT check the type of the operation - it's assumed that this function
2513// will be called from contexts where it's known that the type is contractable.
Craig Toppera97d7e72013-07-26 06:16:11 +00002514static Value* tryEmitFMulAdd(const BinOpInfo &op,
Lang Hames5de91cc2012-10-02 04:45:10 +00002515 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2516 bool isSub=false) {
2517
2518 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
2519 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
2520 "Only fadd/fsub can be the root of an fmuladd.");
2521
2522 // Check whether this op is marked as fusable.
2523 if (!op.FPContractable)
Craig Topper8a13c412014-05-21 05:09:00 +00002524 return nullptr;
Lang Hames5de91cc2012-10-02 04:45:10 +00002525
2526 // Check whether -ffp-contract=on. (If -ffp-contract=off/fast, fusing is
2527 // either disabled, or handled entirely by the LLVM backend).
Lang Hames65992f42012-11-15 07:51:26 +00002528 if (CGF.CGM.getCodeGenOpts().getFPContractMode() != CodeGenOptions::FPC_On)
Craig Topper8a13c412014-05-21 05:09:00 +00002529 return nullptr;
Lang Hames5de91cc2012-10-02 04:45:10 +00002530
2531 // We have a potentially fusable op. Look for a mul on one of the operands.
2532 if (llvm::BinaryOperator* LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
2533 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul) {
Lang Hames4c8559e2012-10-04 03:23:25 +00002534 assert(LHSBinOp->getNumUses() == 0 &&
2535 "Operations with multiple uses shouldn't be contracted.");
Lang Hames5de91cc2012-10-02 04:45:10 +00002536 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
2537 }
2538 } else if (llvm::BinaryOperator* RHSBinOp =
2539 dyn_cast<llvm::BinaryOperator>(op.RHS)) {
2540 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul) {
Lang Hames4c8559e2012-10-04 03:23:25 +00002541 assert(RHSBinOp->getNumUses() == 0 &&
2542 "Operations with multiple uses shouldn't be contracted.");
Lang Hames5de91cc2012-10-02 04:45:10 +00002543 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
2544 }
2545 }
2546
Craig Topper8a13c412014-05-21 05:09:00 +00002547 return nullptr;
Lang Hames5de91cc2012-10-02 04:45:10 +00002548}
2549
John McCall77527a82011-06-25 01:32:37 +00002550Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
2551 if (op.LHS->getType()->isPointerTy() ||
2552 op.RHS->getType()->isPointerTy())
2553 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
2554
2555 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002556 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
John McCall77527a82011-06-25 01:32:37 +00002557 case LangOptions::SOB_Defined:
2558 return Builder.CreateAdd(op.LHS, op.RHS, "add");
Richard Smith3e056de2012-08-25 00:32:28 +00002559 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002560 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith3e056de2012-08-25 00:32:28 +00002561 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2562 // Fall through.
John McCall77527a82011-06-25 01:32:37 +00002563 case LangOptions::SOB_Trapping:
2564 return EmitOverflowCheckedBinOp(op);
2565 }
2566 }
Will Dietz1897cb32012-11-27 15:01:55 +00002567
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002568 if (op.Ty->isUnsignedIntegerType() &&
2569 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow))
Will Dietz1897cb32012-11-27 15:01:55 +00002570 return EmitOverflowCheckedBinOp(op);
2571
Lang Hames5de91cc2012-10-02 04:45:10 +00002572 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2573 // Try to form an fmuladd.
2574 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
2575 return FMulAdd;
2576
John McCall77527a82011-06-25 01:32:37 +00002577 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
Lang Hames5de91cc2012-10-02 04:45:10 +00002578 }
John McCall77527a82011-06-25 01:32:37 +00002579
2580 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2581}
2582
2583Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2584 // The LHS is always a pointer if either side is.
2585 if (!op.LHS->getType()->isPointerTy()) {
2586 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002587 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Chris Lattner51924e512010-06-26 21:25:03 +00002588 case LangOptions::SOB_Defined:
John McCall77527a82011-06-25 01:32:37 +00002589 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Richard Smith3e056de2012-08-25 00:32:28 +00002590 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002591 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith3e056de2012-08-25 00:32:28 +00002592 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2593 // Fall through.
Chris Lattner51924e512010-06-26 21:25:03 +00002594 case LangOptions::SOB_Trapping:
John McCall77527a82011-06-25 01:32:37 +00002595 return EmitOverflowCheckedBinOp(op);
Chris Lattner51924e512010-06-26 21:25:03 +00002596 }
2597 }
Will Dietz1897cb32012-11-27 15:01:55 +00002598
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002599 if (op.Ty->isUnsignedIntegerType() &&
2600 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow))
Will Dietz1897cb32012-11-27 15:01:55 +00002601 return EmitOverflowCheckedBinOp(op);
2602
Lang Hames5de91cc2012-10-02 04:45:10 +00002603 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2604 // Try to form an fmuladd.
2605 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
2606 return FMulAdd;
John McCall77527a82011-06-25 01:32:37 +00002607 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
Lang Hames5de91cc2012-10-02 04:45:10 +00002608 }
Chris Lattner5902e7b2010-03-29 17:28:16 +00002609
John McCall77527a82011-06-25 01:32:37 +00002610 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Mike Stump0c61b732009-04-01 20:28:16 +00002611 }
Chris Lattner3d966d62007-08-24 21:00:35 +00002612
John McCall77527a82011-06-25 01:32:37 +00002613 // If the RHS is not a pointer, then we have normal pointer
2614 // arithmetic.
2615 if (!op.RHS->getType()->isPointerTy())
2616 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
Eli Friedmane381f7e2009-03-28 02:45:41 +00002617
John McCall77527a82011-06-25 01:32:37 +00002618 // Otherwise, this is a pointer subtraction.
Daniel Dunbar42a8cd32009-01-23 18:51:09 +00002619
John McCall77527a82011-06-25 01:32:37 +00002620 // Do the raw subtraction part.
2621 llvm::Value *LHS
2622 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2623 llvm::Value *RHS
2624 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2625 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002626
John McCall77527a82011-06-25 01:32:37 +00002627 // Okay, figure out the element size.
2628 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2629 QualType elementType = expr->getLHS()->getType()->getPointeeType();
Mike Stump4a3999f2009-09-09 13:00:44 +00002630
Craig Topper8a13c412014-05-21 05:09:00 +00002631 llvm::Value *divisor = nullptr;
John McCall77527a82011-06-25 01:32:37 +00002632
2633 // For a variable-length array, this is going to be non-constant.
2634 if (const VariableArrayType *vla
2635 = CGF.getContext().getAsVariableArrayType(elementType)) {
2636 llvm::Value *numElements;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002637 std::tie(numElements, elementType) = CGF.getVLASize(vla);
John McCall77527a82011-06-25 01:32:37 +00002638
2639 divisor = numElements;
2640
2641 // Scale the number of non-VLA elements by the non-VLA element size.
2642 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2643 if (!eltSize.isOne())
2644 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2645
2646 // For everything elese, we can just compute it, safe in the
2647 // assumption that Sema won't let anything through that we can't
2648 // safely compute the size of.
2649 } else {
2650 CharUnits elementSize;
2651 // Handle GCC extension for pointer arithmetic on void* and
2652 // function pointer types.
2653 if (elementType->isVoidType() || elementType->isFunctionType())
2654 elementSize = CharUnits::One();
2655 else
2656 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2657
2658 // Don't even emit the divide for element size of 1.
2659 if (elementSize.isOne())
2660 return diffInChars;
2661
2662 divisor = CGF.CGM.getSize(elementSize);
Chris Lattner2da04b32007-08-24 05:35:26 +00002663 }
Craig Toppera97d7e72013-07-26 06:16:11 +00002664
Chris Lattner2e72da942011-03-01 00:03:48 +00002665 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2666 // pointer difference in C is only defined in the case where both operands
2667 // are pointing to elements of an array.
John McCall77527a82011-06-25 01:32:37 +00002668 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
Chris Lattner2da04b32007-08-24 05:35:26 +00002669}
2670
David Tweed042e0882013-01-07 16:43:27 +00002671Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
David Tweed9fb566c2013-01-10 09:11:33 +00002672 llvm::IntegerType *Ty;
2673 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
2674 Ty = cast<llvm::IntegerType>(VT->getElementType());
2675 else
2676 Ty = cast<llvm::IntegerType>(LHS->getType());
2677 return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
David Tweed042e0882013-01-07 16:43:27 +00002678}
2679
Chris Lattner2da04b32007-08-24 05:35:26 +00002680Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2681 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2682 // RHS to the same size as the LHS.
2683 Value *RHS = Ops.RHS;
2684 if (Ops.LHS->getType() != RHS->getType())
2685 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stump4a3999f2009-09-09 13:00:44 +00002686
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002687 bool SanitizeBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
2688 Ops.Ty->hasSignedIntegerRepresentation();
2689 bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent);
2690 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2691 if (CGF.getLangOpts().OpenCL)
2692 RHS =
2693 Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask");
2694 else if ((SanitizeBase || SanitizeExponent) &&
2695 isa<llvm::IntegerType>(Ops.LHS->getType())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002696 CodeGenFunction::SanitizerScope SanScope(&CGF);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002697 SmallVector<std::pair<Value *, SanitizerKind>, 2> Checks;
Alexey Samsonov48a9db02015-03-05 21:57:35 +00002698 llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, RHS);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002699 llvm::Value *ValidExponent = Builder.CreateICmpULE(RHS, WidthMinusOne);
Richard Smith3e056de2012-08-25 00:32:28 +00002700
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002701 if (SanitizeExponent) {
2702 Checks.push_back(
2703 std::make_pair(ValidExponent, SanitizerKind::ShiftExponent));
2704 }
2705
2706 if (SanitizeBase) {
2707 // Check whether we are shifting any non-zero bits off the top of the
2708 // integer. We only emit this check if exponent is valid - otherwise
2709 // instructions below will have undefined behavior themselves.
Alexey Samsonov48a9db02015-03-05 21:57:35 +00002710 llvm::BasicBlock *Orig = Builder.GetInsertBlock();
2711 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002712 llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check");
2713 Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
2714 CGF.EmitBlock(CheckShiftBase);
Richard Smith3e056de2012-08-25 00:32:28 +00002715 llvm::Value *BitsShiftedOff =
2716 Builder.CreateLShr(Ops.LHS,
2717 Builder.CreateSub(WidthMinusOne, RHS, "shl.zeros",
2718 /*NUW*/true, /*NSW*/true),
2719 "shl.check");
2720 if (CGF.getLangOpts().CPlusPlus) {
2721 // In C99, we are not permitted to shift a 1 bit into the sign bit.
2722 // Under C++11's rules, shifting a 1 bit into the sign bit is
2723 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
2724 // define signed left shifts, so we use the C99 and C++11 rules there).
2725 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
2726 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
2727 }
2728 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002729 llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
Alexey Samsonov48a9db02015-03-05 21:57:35 +00002730 CGF.EmitBlock(Cont);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002731 llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
2732 BaseCheck->addIncoming(Builder.getTrue(), Orig);
2733 BaseCheck->addIncoming(ValidBase, CheckShiftBase);
2734 Checks.push_back(std::make_pair(BaseCheck, SanitizerKind::ShiftBase));
Richard Smith3e056de2012-08-25 00:32:28 +00002735 }
Will Dietz11d0a9f2013-02-25 22:37:49 +00002736
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002737 assert(!Checks.empty());
2738 EmitBinOpCheck(Checks, Ops);
Mike Stumpba6a0c42009-12-14 21:58:14 +00002739 }
2740
Chris Lattner2da04b32007-08-24 05:35:26 +00002741 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2742}
2743
2744Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2745 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2746 // RHS to the same size as the LHS.
2747 Value *RHS = Ops.RHS;
2748 if (Ops.LHS->getType() != RHS->getType())
2749 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stump4a3999f2009-09-09 13:00:44 +00002750
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002751 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2752 if (CGF.getLangOpts().OpenCL)
2753 RHS =
2754 Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask");
2755 else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) &&
2756 isa<llvm::IntegerType>(Ops.LHS->getType())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002757 CodeGenFunction::SanitizerScope SanScope(&CGF);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002758 llvm::Value *Valid =
2759 Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002760 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
Alexey Samsonov24cad992014-07-17 18:46:27 +00002761 }
David Tweed042e0882013-01-07 16:43:27 +00002762
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002763 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00002764 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2765 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2766}
2767
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002768enum IntrinsicType { VCMPEQ, VCMPGT };
2769// return corresponding comparison intrinsic for given vector type
2770static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2771 BuiltinType::Kind ElemKind) {
2772 switch (ElemKind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002773 default: llvm_unreachable("unexpected element type");
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002774 case BuiltinType::Char_U:
2775 case BuiltinType::UChar:
2776 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2777 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002778 case BuiltinType::Char_S:
2779 case BuiltinType::SChar:
2780 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2781 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002782 case BuiltinType::UShort:
2783 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2784 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002785 case BuiltinType::Short:
2786 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2787 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002788 case BuiltinType::UInt:
2789 case BuiltinType::ULong:
2790 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2791 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002792 case BuiltinType::Int:
2793 case BuiltinType::Long:
2794 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2795 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002796 case BuiltinType::Float:
2797 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2798 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002799 }
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002800}
2801
Chris Lattner2da04b32007-08-24 05:35:26 +00002802Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2803 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002804 TestAndClearIgnoreResultAssign();
Chris Lattner42e6b812007-08-26 16:34:22 +00002805 Value *Result;
Chris Lattner2da04b32007-08-24 05:35:26 +00002806 QualType LHSTy = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00002807 QualType RHSTy = E->getRHS()->getType();
John McCall7a9aac22010-08-23 01:21:21 +00002808 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCalle3027922010-08-25 11:45:40 +00002809 assert(E->getOpcode() == BO_EQ ||
2810 E->getOpcode() == BO_NE);
John McCalla1dee5302010-08-22 10:59:02 +00002811 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2812 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall7a9aac22010-08-23 01:21:21 +00002813 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCalle3027922010-08-25 11:45:40 +00002814 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Chandler Carruthb29a7432014-10-11 11:03:30 +00002815 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
Chris Lattner2da04b32007-08-24 05:35:26 +00002816 Value *LHS = Visit(E->getLHS());
2817 Value *RHS = Visit(E->getRHS());
Mike Stump4a3999f2009-09-09 13:00:44 +00002818
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002819 // If AltiVec, the comparison results in a numeric type, so we use
2820 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev93900c72011-03-28 21:00:05 +00002821 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002822 // constants for mapping CR6 register bits to predicate result
2823 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2824
2825 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2826
2827 // in several cases vector arguments order will be reversed
2828 Value *FirstVecArg = LHS,
2829 *SecondVecArg = RHS;
2830
2831 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCall424cec92011-01-19 06:33:43 +00002832 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002833 BuiltinType::Kind ElementKind = BTy->getKind();
2834
2835 switch(E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002836 default: llvm_unreachable("is not a comparison operation");
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002837 case BO_EQ:
2838 CR6 = CR6_LT;
2839 ID = GetIntrinsic(VCMPEQ, ElementKind);
2840 break;
2841 case BO_NE:
2842 CR6 = CR6_EQ;
2843 ID = GetIntrinsic(VCMPEQ, ElementKind);
2844 break;
2845 case BO_LT:
2846 CR6 = CR6_LT;
2847 ID = GetIntrinsic(VCMPGT, ElementKind);
2848 std::swap(FirstVecArg, SecondVecArg);
2849 break;
2850 case BO_GT:
2851 CR6 = CR6_LT;
2852 ID = GetIntrinsic(VCMPGT, ElementKind);
2853 break;
2854 case BO_LE:
2855 if (ElementKind == BuiltinType::Float) {
2856 CR6 = CR6_LT;
2857 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2858 std::swap(FirstVecArg, SecondVecArg);
2859 }
2860 else {
2861 CR6 = CR6_EQ;
2862 ID = GetIntrinsic(VCMPGT, ElementKind);
2863 }
2864 break;
2865 case BO_GE:
2866 if (ElementKind == BuiltinType::Float) {
2867 CR6 = CR6_LT;
2868 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2869 }
2870 else {
2871 CR6 = CR6_EQ;
2872 ID = GetIntrinsic(VCMPGT, ElementKind);
2873 std::swap(FirstVecArg, SecondVecArg);
2874 }
2875 break;
2876 }
2877
Chris Lattner2531eb42011-04-19 22:55:03 +00002878 Value *CR6Param = Builder.getInt32(CR6);
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002879 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2880 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2881 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2882 }
2883
Duncan Sands998f9d92010-02-15 16:14:01 +00002884 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begemanfe79ca22008-07-25 20:16:05 +00002885 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner2da04b32007-08-24 05:35:26 +00002886 LHS, RHS, "cmp");
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002887 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedman3c285242008-05-29 15:09:15 +00002888 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner2da04b32007-08-24 05:35:26 +00002889 LHS, RHS, "cmp");
2890 } else {
Eli Friedman3c285242008-05-29 15:09:15 +00002891 // Unsigned integers and pointers.
2892 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner2da04b32007-08-24 05:35:26 +00002893 LHS, RHS, "cmp");
2894 }
Chris Lattner2a7deb62009-07-08 01:08:03 +00002895
2896 // If this is a vector comparison, sign extend the result to the appropriate
2897 // vector integer type and return it (don't convert to bool).
2898 if (LHSTy->isVectorType())
2899 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stump4a3999f2009-09-09 13:00:44 +00002900
Chris Lattner2da04b32007-08-24 05:35:26 +00002901 } else {
2902 // Complex Comparison: can only be an equality comparison.
Chandler Carruthb29a7432014-10-11 11:03:30 +00002903 CodeGenFunction::ComplexPairTy LHS, RHS;
2904 QualType CETy;
2905 if (auto *CTy = LHSTy->getAs<ComplexType>()) {
2906 LHS = CGF.EmitComplexExpr(E->getLHS());
2907 CETy = CTy->getElementType();
2908 } else {
2909 LHS.first = Visit(E->getLHS());
2910 LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
2911 CETy = LHSTy;
2912 }
2913 if (auto *CTy = RHSTy->getAs<ComplexType>()) {
2914 RHS = CGF.EmitComplexExpr(E->getRHS());
2915 assert(CGF.getContext().hasSameUnqualifiedType(CETy,
2916 CTy->getElementType()) &&
2917 "The element types must always match.");
Chandler Carruth60fdc412014-10-11 11:29:26 +00002918 (void)CTy;
Chandler Carruthb29a7432014-10-11 11:03:30 +00002919 } else {
2920 RHS.first = Visit(E->getRHS());
2921 RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
2922 assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
2923 "The element types must always match.");
2924 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002925
Chris Lattner42e6b812007-08-26 16:34:22 +00002926 Value *ResultR, *ResultI;
Chris Lattner2da04b32007-08-24 05:35:26 +00002927 if (CETy->isRealFloatingType()) {
2928 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2929 LHS.first, RHS.first, "cmp.r");
2930 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2931 LHS.second, RHS.second, "cmp.i");
2932 } else {
2933 // Complex comparisons can only be equality comparisons. As such, signed
2934 // and unsigned opcodes are the same.
2935 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2936 LHS.first, RHS.first, "cmp.r");
2937 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2938 LHS.second, RHS.second, "cmp.i");
2939 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002940
John McCalle3027922010-08-25 11:45:40 +00002941 if (E->getOpcode() == BO_EQ) {
Chris Lattner2da04b32007-08-24 05:35:26 +00002942 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2943 } else {
John McCalle3027922010-08-25 11:45:40 +00002944 assert(E->getOpcode() == BO_NE &&
Chris Lattner2da04b32007-08-24 05:35:26 +00002945 "Complex comparison other than == or != ?");
2946 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2947 }
2948 }
Nuno Lopesa0abe622009-01-11 23:22:37 +00002949
2950 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner2da04b32007-08-24 05:35:26 +00002951}
2952
2953Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002954 bool Ignore = TestAndClearIgnoreResultAssign();
2955
John McCall31168b02011-06-15 23:02:42 +00002956 Value *RHS;
2957 LValue LHS;
Mike Stump4a3999f2009-09-09 13:00:44 +00002958
John McCall31168b02011-06-15 23:02:42 +00002959 switch (E->getLHS()->getType().getObjCLifetime()) {
2960 case Qualifiers::OCL_Strong:
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002961 std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
John McCall31168b02011-06-15 23:02:42 +00002962 break;
2963
2964 case Qualifiers::OCL_Autoreleasing:
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002965 std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
John McCall31168b02011-06-15 23:02:42 +00002966 break;
2967
2968 case Qualifiers::OCL_Weak:
2969 RHS = Visit(E->getRHS());
Richard Smith4d1458e2012-09-08 02:08:36 +00002970 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCall31168b02011-06-15 23:02:42 +00002971 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2972 break;
2973
2974 // No reason to do any of these differently.
2975 case Qualifiers::OCL_None:
2976 case Qualifiers::OCL_ExplicitNone:
2977 // __block variables need to have the rhs evaluated first, plus
2978 // this should improve codegen just a little.
2979 RHS = Visit(E->getRHS());
Richard Smith4d1458e2012-09-08 02:08:36 +00002980 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCall31168b02011-06-15 23:02:42 +00002981
2982 // Store the value into the LHS. Bit-fields are handled specially
2983 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2984 // 'An assignment expression has the value of the left operand after
2985 // the assignment...'.
2986 if (LHS.isBitField())
John McCall55e1fbc2011-06-25 02:11:03 +00002987 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
John McCall31168b02011-06-15 23:02:42 +00002988 else
John McCall55e1fbc2011-06-25 02:11:03 +00002989 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
John McCall31168b02011-06-15 23:02:42 +00002990 }
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002991
2992 // If the result is clearly ignored, return now.
Mike Stumpdf0fe272009-05-29 15:46:01 +00002993 if (Ignore)
Craig Topper8a13c412014-05-21 05:09:00 +00002994 return nullptr;
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002995
John McCall07bb1962010-11-16 10:08:07 +00002996 // The result of an assignment in C is the assigned r-value.
Richard Smith9c6890a2012-11-01 22:30:59 +00002997 if (!CGF.getLangOpts().CPlusPlus)
John McCall07bb1962010-11-16 10:08:07 +00002998 return RHS;
2999
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003000 // If the lvalue is non-volatile, return the computed value of the assignment.
3001 if (!LHS.isVolatileQualified())
3002 return RHS;
3003
3004 // Otherwise, reload the value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00003005 return EmitLoadOfLValue(LHS, E->getExprLoc());
Chris Lattner2da04b32007-08-24 05:35:26 +00003006}
3007
3008Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Justin Bogneref512b92014-01-06 22:27:43 +00003009 RegionCounter Cnt = CGF.getPGORegionCounter(E);
3010
Tanya Lattner20248222012-01-16 21:02:28 +00003011 // Perform vector logical and on comparisons with zero vectors.
3012 if (E->getType()->isVectorType()) {
Justin Bogneref512b92014-01-06 22:27:43 +00003013 Cnt.beginRegion(Builder);
3014
Tanya Lattner20248222012-01-16 21:02:28 +00003015 Value *LHS = Visit(E->getLHS());
3016 Value *RHS = Visit(E->getRHS());
3017 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
Joey Gouly7d00f002013-02-21 11:49:56 +00003018 if (LHS->getType()->isFPOrFPVectorTy()) {
3019 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
3020 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
3021 } else {
3022 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
3023 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
3024 }
Tanya Lattner20248222012-01-16 21:02:28 +00003025 Value *And = Builder.CreateAnd(LHS, RHS);
Joey Gouly7d00f002013-02-21 11:49:56 +00003026 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
Tanya Lattner20248222012-01-16 21:02:28 +00003027 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003028
Chris Lattner2192fe52011-07-18 04:24:23 +00003029 llvm::Type *ResTy = ConvertType(E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00003030
Chris Lattner8b084582008-11-12 08:26:50 +00003031 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
3032 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattner41c6ab52011-02-27 23:02:32 +00003033 bool LHSCondVal;
3034 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
3035 if (LHSCondVal) { // If we have 1 && X, just emit X.
Justin Bogneref512b92014-01-06 22:27:43 +00003036 Cnt.beginRegion(Builder);
3037
Chris Lattner5b1964b2008-11-11 07:41:27 +00003038 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner671fec82009-10-17 04:24:20 +00003039 // ZExt result to int or bool.
3040 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner5b1964b2008-11-11 07:41:27 +00003041 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003042
Chris Lattner671fec82009-10-17 04:24:20 +00003043 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner8b084582008-11-12 08:26:50 +00003044 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner671fec82009-10-17 04:24:20 +00003045 return llvm::Constant::getNullValue(ResTy);
Chris Lattner5b1964b2008-11-11 07:41:27 +00003046 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003047
Daniel Dunbara612e792008-11-13 01:38:36 +00003048 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
3049 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner8b084582008-11-12 08:26:50 +00003050
John McCallce1de612011-01-26 04:00:11 +00003051 CodeGenFunction::ConditionalEvaluation eval(CGF);
3052
Chris Lattner35710d182008-11-12 08:38:24 +00003053 // Branch on the LHS first. If it is false, go to the failure (cont) block.
Justin Bogneref512b92014-01-06 22:27:43 +00003054 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock, Cnt.getCount());
Chris Lattner35710d182008-11-12 08:38:24 +00003055
3056 // Any edges into the ContBlock are now from an (indeterminate number of)
3057 // edges from this first condition. All of these values will be false. Start
3058 // setting up the PHI node in the Cont Block for this.
Jay Foad20c0f022011-03-30 11:28:58 +00003059 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson41a75022009-08-13 21:57:51 +00003060 "", ContBlock);
Chris Lattner35710d182008-11-12 08:38:24 +00003061 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
3062 PI != PE; ++PI)
Owen Andersonfe4e3472009-07-31 17:39:36 +00003063 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stump4a3999f2009-09-09 13:00:44 +00003064
John McCallce1de612011-01-26 04:00:11 +00003065 eval.begin(CGF);
Chris Lattner2da04b32007-08-24 05:35:26 +00003066 CGF.EmitBlock(RHSBlock);
Justin Bogneref512b92014-01-06 22:27:43 +00003067 Cnt.beginRegion(Builder);
Chris Lattner2da04b32007-08-24 05:35:26 +00003068 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCallce1de612011-01-26 04:00:11 +00003069 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00003070
Chris Lattner2da04b32007-08-24 05:35:26 +00003071 // Reaquire the RHS block, as there may be subblocks inserted.
3072 RHSBlock = Builder.GetInsertBlock();
Chris Lattner35710d182008-11-12 08:38:24 +00003073
David Blaikie1b5adb82014-07-10 20:42:59 +00003074 // Emit an unconditional branch from this block to ContBlock.
3075 {
Devang Patel4d761272011-03-30 00:08:31 +00003076 // There is no need to emit line number for unconditional branch.
Adrian Prantl95b24e92015-02-03 20:00:54 +00003077 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
David Blaikie1b5adb82014-07-10 20:42:59 +00003078 CGF.EmitBlock(ContBlock);
3079 }
3080 // Insert an entry into the phi node for the edge with the value of RHSCond.
Chris Lattner2da04b32007-08-24 05:35:26 +00003081 PN->addIncoming(RHSCond, RHSBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00003082
Chris Lattner2da04b32007-08-24 05:35:26 +00003083 // ZExt result to int.
Chris Lattner671fec82009-10-17 04:24:20 +00003084 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00003085}
3086
3087Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Justin Bogneref512b92014-01-06 22:27:43 +00003088 RegionCounter Cnt = CGF.getPGORegionCounter(E);
3089
Tanya Lattner20248222012-01-16 21:02:28 +00003090 // Perform vector logical or on comparisons with zero vectors.
3091 if (E->getType()->isVectorType()) {
Justin Bogneref512b92014-01-06 22:27:43 +00003092 Cnt.beginRegion(Builder);
3093
Tanya Lattner20248222012-01-16 21:02:28 +00003094 Value *LHS = Visit(E->getLHS());
3095 Value *RHS = Visit(E->getRHS());
3096 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
Joey Gouly7d00f002013-02-21 11:49:56 +00003097 if (LHS->getType()->isFPOrFPVectorTy()) {
3098 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
3099 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
3100 } else {
3101 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
3102 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
3103 }
Tanya Lattner20248222012-01-16 21:02:28 +00003104 Value *Or = Builder.CreateOr(LHS, RHS);
Joey Gouly7d00f002013-02-21 11:49:56 +00003105 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
Tanya Lattner20248222012-01-16 21:02:28 +00003106 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003107
Chris Lattner2192fe52011-07-18 04:24:23 +00003108 llvm::Type *ResTy = ConvertType(E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00003109
Chris Lattner8b084582008-11-12 08:26:50 +00003110 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
3111 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattner41c6ab52011-02-27 23:02:32 +00003112 bool LHSCondVal;
3113 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
3114 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Justin Bogneref512b92014-01-06 22:27:43 +00003115 Cnt.beginRegion(Builder);
3116
Chris Lattner5b1964b2008-11-11 07:41:27 +00003117 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner671fec82009-10-17 04:24:20 +00003118 // ZExt result to int or bool.
3119 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner5b1964b2008-11-11 07:41:27 +00003120 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003121
Chris Lattner671fec82009-10-17 04:24:20 +00003122 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner8b084582008-11-12 08:26:50 +00003123 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner671fec82009-10-17 04:24:20 +00003124 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner5b1964b2008-11-11 07:41:27 +00003125 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003126
Daniel Dunbara612e792008-11-13 01:38:36 +00003127 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
3128 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stump4a3999f2009-09-09 13:00:44 +00003129
John McCallce1de612011-01-26 04:00:11 +00003130 CodeGenFunction::ConditionalEvaluation eval(CGF);
3131
Chris Lattner35710d182008-11-12 08:38:24 +00003132 // Branch on the LHS first. If it is true, go to the success (cont) block.
Justin Bogneref512b92014-01-06 22:27:43 +00003133 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
3134 Cnt.getParentCount() - Cnt.getCount());
Chris Lattner35710d182008-11-12 08:38:24 +00003135
3136 // Any edges into the ContBlock are now from an (indeterminate number of)
3137 // edges from this first condition. All of these values will be true. Start
3138 // setting up the PHI node in the Cont Block for this.
Jay Foad20c0f022011-03-30 11:28:58 +00003139 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson41a75022009-08-13 21:57:51 +00003140 "", ContBlock);
Chris Lattner35710d182008-11-12 08:38:24 +00003141 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
3142 PI != PE; ++PI)
Owen Andersonfe4e3472009-07-31 17:39:36 +00003143 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattner35710d182008-11-12 08:38:24 +00003144
John McCallce1de612011-01-26 04:00:11 +00003145 eval.begin(CGF);
Anders Carlssonf47a3de2009-06-04 02:53:13 +00003146
Chris Lattner35710d182008-11-12 08:38:24 +00003147 // Emit the RHS condition as a bool value.
Chris Lattner2da04b32007-08-24 05:35:26 +00003148 CGF.EmitBlock(RHSBlock);
Justin Bogneref512b92014-01-06 22:27:43 +00003149 Cnt.beginRegion(Builder);
Chris Lattner2da04b32007-08-24 05:35:26 +00003150 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stump4a3999f2009-09-09 13:00:44 +00003151
John McCallce1de612011-01-26 04:00:11 +00003152 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00003153
Chris Lattner2da04b32007-08-24 05:35:26 +00003154 // Reaquire the RHS block, as there may be subblocks inserted.
3155 RHSBlock = Builder.GetInsertBlock();
Mike Stump4a3999f2009-09-09 13:00:44 +00003156
Chris Lattner35710d182008-11-12 08:38:24 +00003157 // Emit an unconditional branch from this block to ContBlock. Insert an entry
3158 // into the phi node for the edge with the value of RHSCond.
3159 CGF.EmitBlock(ContBlock);
Chris Lattner2da04b32007-08-24 05:35:26 +00003160 PN->addIncoming(RHSCond, RHSBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00003161
Chris Lattner2da04b32007-08-24 05:35:26 +00003162 // ZExt result to int.
Chris Lattner671fec82009-10-17 04:24:20 +00003163 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00003164}
3165
3166Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCalla2342eb2010-12-05 02:00:02 +00003167 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00003168 CGF.EnsureInsertPoint();
Chris Lattner2da04b32007-08-24 05:35:26 +00003169 return Visit(E->getRHS());
3170}
3171
3172//===----------------------------------------------------------------------===//
3173// Other Operators
3174//===----------------------------------------------------------------------===//
3175
Chris Lattner3fd91f832008-11-12 08:55:54 +00003176/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
3177/// expression is cheap enough and side-effect-free enough to evaluate
3178/// unconditionally instead of conditionally. This is used to convert control
3179/// flow into selects in some cases.
Mike Stump53f9ded2009-11-03 23:25:48 +00003180static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
3181 CodeGenFunction &CGF) {
Chris Lattner56784f92011-04-16 23:15:35 +00003182 // Anything that is an integer or floating point constant is fine.
Nick Lewycky22e55a02013-11-08 23:00:12 +00003183 return E->IgnoreParens()->isEvaluatable(CGF.getContext());
Mike Stump4a3999f2009-09-09 13:00:44 +00003184
Nick Lewycky22e55a02013-11-08 23:00:12 +00003185 // Even non-volatile automatic variables can't be evaluated unconditionally.
3186 // Referencing a thread_local may cause non-trivial initialization work to
3187 // occur. If we're inside a lambda and one of the variables is from the scope
3188 // outside the lambda, that function may have returned already. Reading its
3189 // locals is a bad idea. Also, these reads may introduce races there didn't
3190 // exist in the source-level program.
Chris Lattner3fd91f832008-11-12 08:55:54 +00003191}
3192
3193
Chris Lattner2da04b32007-08-24 05:35:26 +00003194Value *ScalarExprEmitter::
John McCallc07a0c72011-02-17 10:25:35 +00003195VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00003196 TestAndClearIgnoreResultAssign();
John McCallc07a0c72011-02-17 10:25:35 +00003197
3198 // Bind the common expression if necessary.
Eli Friedman48fd89a2012-01-06 20:42:20 +00003199 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
Justin Bogneref512b92014-01-06 22:27:43 +00003200 RegionCounter Cnt = CGF.getPGORegionCounter(E);
John McCallc07a0c72011-02-17 10:25:35 +00003201
3202 Expr *condExpr = E->getCond();
3203 Expr *lhsExpr = E->getTrueExpr();
3204 Expr *rhsExpr = E->getFalseExpr();
3205
Chris Lattnercd439292008-11-12 08:04:58 +00003206 // If the condition constant folds and can be elided, try to avoid emitting
3207 // the condition and the dead arm.
Chris Lattner41c6ab52011-02-27 23:02:32 +00003208 bool CondExprBool;
3209 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003210 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattner41c6ab52011-02-27 23:02:32 +00003211 if (!CondExprBool) std::swap(live, dead);
Mike Stump4a3999f2009-09-09 13:00:44 +00003212
Eli Friedman27ef75b2011-10-15 02:10:40 +00003213 // If the dead side doesn't have labels we need, just emit the Live part.
3214 if (!CGF.ContainsLabel(dead)) {
Justin Bogneref512b92014-01-06 22:27:43 +00003215 if (CondExprBool)
3216 Cnt.beginRegion(Builder);
Eli Friedman27ef75b2011-10-15 02:10:40 +00003217 Value *Result = Visit(live);
3218
3219 // If the live part is a throw expression, it acts like it has a void
3220 // type, so evaluating it returns a null Value*. However, a conditional
3221 // with non-void type must return a non-null Value*.
3222 if (!Result && !E->getType()->isVoidType())
3223 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
3224
3225 return Result;
3226 }
Chris Lattnerd53e2332008-11-11 18:56:45 +00003227 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003228
Nate Begemanabb5a732010-09-20 22:41:17 +00003229 // OpenCL: If the condition is a vector, we can treat this condition like
3230 // the select function.
Craig Toppera97d7e72013-07-26 06:16:11 +00003231 if (CGF.getLangOpts().OpenCL
John McCallc07a0c72011-02-17 10:25:35 +00003232 && condExpr->getType()->isVectorType()) {
Justin Bogneref512b92014-01-06 22:27:43 +00003233 Cnt.beginRegion(Builder);
3234
John McCallc07a0c72011-02-17 10:25:35 +00003235 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
3236 llvm::Value *LHS = Visit(lhsExpr);
3237 llvm::Value *RHS = Visit(rhsExpr);
Craig Toppera97d7e72013-07-26 06:16:11 +00003238
Chris Lattner2192fe52011-07-18 04:24:23 +00003239 llvm::Type *condType = ConvertType(condExpr->getType());
3240 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
Craig Toppera97d7e72013-07-26 06:16:11 +00003241
3242 unsigned numElem = vecTy->getNumElements();
Chris Lattner2192fe52011-07-18 04:24:23 +00003243 llvm::Type *elemType = vecTy->getElementType();
Craig Toppera97d7e72013-07-26 06:16:11 +00003244
Chris Lattner2d6b7b92012-01-25 05:34:41 +00003245 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
Nate Begemanabb5a732010-09-20 22:41:17 +00003246 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
Craig Toppera97d7e72013-07-26 06:16:11 +00003247 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
Nate Begemanabb5a732010-09-20 22:41:17 +00003248 llvm::VectorType::get(elemType,
Craig Toppera97d7e72013-07-26 06:16:11 +00003249 numElem),
Nate Begemanabb5a732010-09-20 22:41:17 +00003250 "sext");
3251 llvm::Value *tmp2 = Builder.CreateNot(tmp);
Craig Toppera97d7e72013-07-26 06:16:11 +00003252
Nate Begemanabb5a732010-09-20 22:41:17 +00003253 // Cast float to int to perform ANDs if necessary.
3254 llvm::Value *RHSTmp = RHS;
3255 llvm::Value *LHSTmp = LHS;
3256 bool wasCast = false;
Chris Lattner2192fe52011-07-18 04:24:23 +00003257 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
Peter Collingbourneaac265c2012-05-29 00:35:18 +00003258 if (rhsVTy->getElementType()->isFloatingPointTy()) {
Nate Begemanabb5a732010-09-20 22:41:17 +00003259 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
3260 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
3261 wasCast = true;
3262 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003263
Nate Begemanabb5a732010-09-20 22:41:17 +00003264 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
3265 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
3266 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
3267 if (wasCast)
3268 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
3269
3270 return tmp5;
3271 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003272
Chris Lattner3fd91f832008-11-12 08:55:54 +00003273 // If this is a really simple expression (like x ? 4 : 5), emit this as a
3274 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner9ce8a532008-11-16 06:16:27 +00003275 // safe to evaluate the LHS and RHS unconditionally.
John McCallc07a0c72011-02-17 10:25:35 +00003276 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
3277 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
Justin Bogneref512b92014-01-06 22:27:43 +00003278 Cnt.beginRegion(Builder);
3279
John McCallc07a0c72011-02-17 10:25:35 +00003280 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
3281 llvm::Value *LHS = Visit(lhsExpr);
3282 llvm::Value *RHS = Visit(rhsExpr);
Eli Friedman516c2ad2011-12-08 22:01:56 +00003283 if (!LHS) {
3284 // If the conditional has void type, make sure we return a null Value*.
3285 assert(!RHS && "LHS and RHS types must match");
Craig Topper8a13c412014-05-21 05:09:00 +00003286 return nullptr;
Eli Friedman516c2ad2011-12-08 22:01:56 +00003287 }
Chris Lattner3fd91f832008-11-12 08:55:54 +00003288 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
3289 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003290
Daniel Dunbard2a53a72008-11-12 10:13:37 +00003291 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
3292 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbara612e792008-11-13 01:38:36 +00003293 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCallce1de612011-01-26 04:00:11 +00003294
3295 CodeGenFunction::ConditionalEvaluation eval(CGF);
Justin Bogneref512b92014-01-06 22:27:43 +00003296 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock, Cnt.getCount());
Anders Carlsson43c52cd2009-06-04 03:00:32 +00003297
Chris Lattner2da04b32007-08-24 05:35:26 +00003298 CGF.EmitBlock(LHSBlock);
Justin Bogneref512b92014-01-06 22:27:43 +00003299 Cnt.beginRegion(Builder);
John McCallce1de612011-01-26 04:00:11 +00003300 eval.begin(CGF);
John McCallc07a0c72011-02-17 10:25:35 +00003301 Value *LHS = Visit(lhsExpr);
John McCallce1de612011-01-26 04:00:11 +00003302 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00003303
Chris Lattner2da04b32007-08-24 05:35:26 +00003304 LHSBlock = Builder.GetInsertBlock();
John McCallce1de612011-01-26 04:00:11 +00003305 Builder.CreateBr(ContBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00003306
Chris Lattner2da04b32007-08-24 05:35:26 +00003307 CGF.EmitBlock(RHSBlock);
John McCallce1de612011-01-26 04:00:11 +00003308 eval.begin(CGF);
John McCallc07a0c72011-02-17 10:25:35 +00003309 Value *RHS = Visit(rhsExpr);
John McCallce1de612011-01-26 04:00:11 +00003310 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00003311
John McCallce1de612011-01-26 04:00:11 +00003312 RHSBlock = Builder.GetInsertBlock();
Chris Lattner2da04b32007-08-24 05:35:26 +00003313 CGF.EmitBlock(ContBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00003314
Eli Friedmanf6c175b2009-12-07 20:25:53 +00003315 // If the LHS or RHS is a throw expression, it will be legitimately null.
3316 if (!LHS)
3317 return RHS;
3318 if (!RHS)
3319 return LHS;
Mike Stump4a3999f2009-09-09 13:00:44 +00003320
Chris Lattner2da04b32007-08-24 05:35:26 +00003321 // Create a PHI node for the real part.
Jay Foad20c0f022011-03-30 11:28:58 +00003322 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
Chris Lattner2da04b32007-08-24 05:35:26 +00003323 PN->addIncoming(LHS, LHSBlock);
3324 PN->addIncoming(RHS, RHSBlock);
3325 return PN;
3326}
3327
3328Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman75807f22013-07-20 00:40:58 +00003329 return Visit(E->getChosenSubExpr());
Chris Lattner2da04b32007-08-24 05:35:26 +00003330}
3331
Chris Lattnerb6a7b582007-11-30 17:56:23 +00003332Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Richard Smitha1a808c2014-04-14 23:47:48 +00003333 QualType Ty = VE->getType();
Daniel Sanders59229dc2014-11-19 10:01:35 +00003334
Richard Smitha1a808c2014-04-14 23:47:48 +00003335 if (Ty->isVariablyModifiedType())
3336 CGF.EmitVariablyModifiedType(Ty);
3337
Eli Friedmanddea0ad2009-01-20 17:46:04 +00003338 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlsson13abd7e2008-11-04 05:30:00 +00003339 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00003340 llvm::Type *ArgTy = ConvertType(VE->getType());
Anders Carlsson13abd7e2008-11-04 05:30:00 +00003341
3342 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stump4a3999f2009-09-09 13:00:44 +00003343 if (!ArgPtr)
Daniel Sanders59229dc2014-11-19 10:01:35 +00003344 return Builder.CreateVAArg(ArgValue, ArgTy);
Anders Carlsson13abd7e2008-11-04 05:30:00 +00003345
Mike Stumpdf0fe272009-05-29 15:46:01 +00003346 // FIXME Volatility.
Daniel Sanders59229dc2014-11-19 10:01:35 +00003347 llvm::Value *Val = Builder.CreateLoad(ArgPtr);
3348
3349 // If EmitVAArg promoted the type, we must truncate it.
Daniel Sanderscdcb5802015-01-13 10:47:00 +00003350 if (ArgTy != Val->getType()) {
3351 if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
3352 Val = Builder.CreateIntToPtr(Val, ArgTy);
3353 else
3354 Val = Builder.CreateTrunc(Val, ArgTy);
3355 }
Daniel Sanders59229dc2014-11-19 10:01:35 +00003356
3357 return Val;
Anders Carlsson7e13ab82007-10-15 20:28:48 +00003358}
3359
John McCall351762c2011-02-07 10:33:21 +00003360Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
3361 return CGF.EmitBlockLiteral(block);
Mike Stumpab3afd82009-02-12 18:29:15 +00003362}
3363
Tanya Lattner55808c12011-06-04 00:47:47 +00003364Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
3365 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
Chris Lattner2192fe52011-07-18 04:24:23 +00003366 llvm::Type *DstTy = ConvertType(E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00003367
Tanya Lattner55808c12011-06-04 00:47:47 +00003368 // Going from vec4->vec3 or vec3->vec4 is a special case and requires
3369 // a shuffle vector instead of a bitcast.
Chris Lattner2192fe52011-07-18 04:24:23 +00003370 llvm::Type *SrcTy = Src->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003371 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
3372 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
3373 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
Craig Toppera97d7e72013-07-26 06:16:11 +00003374 if ((numElementsDst == 3 && numElementsSrc == 4)
Tanya Lattner55808c12011-06-04 00:47:47 +00003375 || (numElementsDst == 4 && numElementsSrc == 3)) {
Craig Toppera97d7e72013-07-26 06:16:11 +00003376
3377
Tanya Lattner55808c12011-06-04 00:47:47 +00003378 // In the case of going from int4->float3, a bitcast is needed before
3379 // doing a shuffle.
Craig Toppera97d7e72013-07-26 06:16:11 +00003380 llvm::Type *srcElemTy =
Tanya Lattner55808c12011-06-04 00:47:47 +00003381 cast<llvm::VectorType>(SrcTy)->getElementType();
Craig Toppera97d7e72013-07-26 06:16:11 +00003382 llvm::Type *dstElemTy =
Tanya Lattner55808c12011-06-04 00:47:47 +00003383 cast<llvm::VectorType>(DstTy)->getElementType();
Craig Toppera97d7e72013-07-26 06:16:11 +00003384
Tanya Lattner55808c12011-06-04 00:47:47 +00003385 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
3386 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
3387 // Create a float type of the same size as the source or destination.
Chris Lattner2192fe52011-07-18 04:24:23 +00003388 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003389 numElementsSrc);
Craig Toppera97d7e72013-07-26 06:16:11 +00003390
Tanya Lattner55808c12011-06-04 00:47:47 +00003391 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
3392 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003393
Tanya Lattner55808c12011-06-04 00:47:47 +00003394 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00003395
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003396 SmallVector<llvm::Constant*, 3> Args;
Tanya Lattner55808c12011-06-04 00:47:47 +00003397 Args.push_back(Builder.getInt32(0));
3398 Args.push_back(Builder.getInt32(1));
3399 Args.push_back(Builder.getInt32(2));
Craig Toppera97d7e72013-07-26 06:16:11 +00003400
Tanya Lattner55808c12011-06-04 00:47:47 +00003401 if (numElementsDst == 4)
Chris Lattnerece04092012-02-07 00:39:47 +00003402 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Craig Toppera97d7e72013-07-26 06:16:11 +00003403
Tanya Lattner55808c12011-06-04 00:47:47 +00003404 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Craig Toppera97d7e72013-07-26 06:16:11 +00003405
Tanya Lattner55808c12011-06-04 00:47:47 +00003406 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
3407 }
3408 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003409
Tanya Lattner55808c12011-06-04 00:47:47 +00003410 return Builder.CreateBitCast(Src, DstTy, "astype");
3411}
3412
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003413Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
3414 return CGF.EmitAtomicExpr(E).getScalarVal();
3415}
3416
Chris Lattner2da04b32007-08-24 05:35:26 +00003417//===----------------------------------------------------------------------===//
3418// Entry Point into this File
3419//===----------------------------------------------------------------------===//
3420
Mike Stump4a3999f2009-09-09 13:00:44 +00003421/// EmitScalarExpr - Emit the computation of the specified expression of scalar
3422/// type, ignoring the result.
Mike Stumpdf0fe272009-05-29 15:46:01 +00003423Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
John McCall47fb9502013-03-07 21:37:08 +00003424 assert(E && hasScalarEvaluationKind(E->getType()) &&
Chris Lattner2da04b32007-08-24 05:35:26 +00003425 "Invalid scalar expression to emit");
Mike Stump4a3999f2009-09-09 13:00:44 +00003426
David Blaikie38b25912015-02-09 19:13:51 +00003427 return ScalarExprEmitter(*this, IgnoreResultAssign)
3428 .Visit(const_cast<Expr *>(E));
Chris Lattner2da04b32007-08-24 05:35:26 +00003429}
Chris Lattner3474c202007-08-26 06:48:56 +00003430
3431/// EmitScalarConversion - Emit a conversion from the specified type to the
3432/// specified destination type, both of which are LLVM scalar types.
Chris Lattner42e6b812007-08-26 16:34:22 +00003433Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
3434 QualType DstTy) {
John McCall47fb9502013-03-07 21:37:08 +00003435 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
Chris Lattner3474c202007-08-26 06:48:56 +00003436 "Invalid scalar expression to emit");
3437 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
3438}
Chris Lattner42e6b812007-08-26 16:34:22 +00003439
Mike Stump4a3999f2009-09-09 13:00:44 +00003440/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
3441/// type to the specified destination type, where the destination type is an
3442/// LLVM scalar type.
Chris Lattner42e6b812007-08-26 16:34:22 +00003443Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
3444 QualType SrcTy,
3445 QualType DstTy) {
John McCall47fb9502013-03-07 21:37:08 +00003446 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
Chris Lattner42e6b812007-08-26 16:34:22 +00003447 "Invalid complex -> scalar conversion");
3448 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
3449 DstTy);
3450}
Anders Carlssonb9eb82c2007-12-10 19:35:18 +00003451
Chris Lattner05dc78c2010-06-26 22:09:34 +00003452
3453llvm::Value *CodeGenFunction::
3454EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
3455 bool isInc, bool isPre) {
3456 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
3457}
3458
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00003459LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
3460 llvm::Value *V;
3461 // object->isa or (*object).isa
3462 // Generate code as for: *(Class*)object
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00003463 // build Class* type
Chris Lattner2192fe52011-07-18 04:24:23 +00003464 llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahaniandf506b92010-02-05 19:18:30 +00003465
3466 Expr *BaseExpr = E->getBase();
John McCall086a4642010-11-24 05:12:34 +00003467 if (BaseExpr->isRValue()) {
Eli Friedman3184a5e2011-12-19 23:03:09 +00003468 V = CreateMemTemp(E->getType(), "resval");
Fariborz Jahaniandf506b92010-02-05 19:18:30 +00003469 llvm::Value *Src = EmitScalarExpr(BaseExpr);
3470 Builder.CreateStore(Src, V);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00003471 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
Nick Lewycky2d84e842013-10-02 02:29:49 +00003472 MakeNaturalAlignAddrLValue(V, E->getType()), E->getExprLoc());
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00003473 } else {
3474 if (E->isArrow())
3475 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
3476 else
3477 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahaniandf506b92010-02-05 19:18:30 +00003478 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003479
Fariborz Jahaniandf506b92010-02-05 19:18:30 +00003480 // build Class* type
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00003481 ClassPtrTy = ClassPtrTy->getPointerTo();
3482 V = Builder.CreateBitCast(V, ClassPtrTy);
Eli Friedman3184a5e2011-12-19 23:03:09 +00003483 return MakeNaturalAlignAddrLValue(V, E->getType());
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00003484}
3485
Douglas Gregor914af212010-04-23 04:16:32 +00003486
John McCalla2342eb2010-12-05 02:00:02 +00003487LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor914af212010-04-23 04:16:32 +00003488 const CompoundAssignOperator *E) {
3489 ScalarExprEmitter Scalar(*this);
Craig Topper8a13c412014-05-21 05:09:00 +00003490 Value *Result = nullptr;
Douglas Gregor914af212010-04-23 04:16:32 +00003491 switch (E->getOpcode()) {
3492#define COMPOUND_OP(Op) \
John McCalle3027922010-08-25 11:45:40 +00003493 case BO_##Op##Assign: \
Douglas Gregor914af212010-04-23 04:16:32 +00003494 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003495 Result)
Douglas Gregor914af212010-04-23 04:16:32 +00003496 COMPOUND_OP(Mul);
3497 COMPOUND_OP(Div);
3498 COMPOUND_OP(Rem);
3499 COMPOUND_OP(Add);
3500 COMPOUND_OP(Sub);
3501 COMPOUND_OP(Shl);
3502 COMPOUND_OP(Shr);
3503 COMPOUND_OP(And);
3504 COMPOUND_OP(Xor);
3505 COMPOUND_OP(Or);
3506#undef COMPOUND_OP
Craig Toppera97d7e72013-07-26 06:16:11 +00003507
John McCalle3027922010-08-25 11:45:40 +00003508 case BO_PtrMemD:
3509 case BO_PtrMemI:
3510 case BO_Mul:
3511 case BO_Div:
3512 case BO_Rem:
3513 case BO_Add:
3514 case BO_Sub:
3515 case BO_Shl:
3516 case BO_Shr:
3517 case BO_LT:
3518 case BO_GT:
3519 case BO_LE:
3520 case BO_GE:
3521 case BO_EQ:
3522 case BO_NE:
3523 case BO_And:
3524 case BO_Xor:
3525 case BO_Or:
3526 case BO_LAnd:
3527 case BO_LOr:
3528 case BO_Assign:
3529 case BO_Comma:
David Blaikie83d382b2011-09-23 05:06:16 +00003530 llvm_unreachable("Not valid compound assignment operators");
Douglas Gregor914af212010-04-23 04:16:32 +00003531 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003532
Douglas Gregor914af212010-04-23 04:16:32 +00003533 llvm_unreachable("Unhandled compound assignment operator");
3534}