CGExprScalar.cpp revision 31a0984b5cb4af99d2407c0f25bf5af68df681c6
1//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This contains code to emit Expr nodes with scalar LLVM types as LLVM code. 11// 12//===----------------------------------------------------------------------===// 13 14#include "CodeGenFunction.h" 15#include "CodeGenModule.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/DeclObjC.h" 18#include "clang/AST/StmtVisitor.h" 19#include "clang/Basic/TargetInfo.h" 20#include "llvm/Constants.h" 21#include "llvm/Function.h" 22#include "llvm/GlobalVariable.h" 23#include "llvm/Intrinsics.h" 24#include "llvm/Support/Compiler.h" 25#include <cstdarg> 26 27using namespace clang; 28using namespace CodeGen; 29using llvm::Value; 30 31//===----------------------------------------------------------------------===// 32// Scalar Expression Emitter 33//===----------------------------------------------------------------------===// 34 35struct BinOpInfo { 36 Value *LHS; 37 Value *RHS; 38 QualType Ty; // Computation Type. 39 const BinaryOperator *E; 40}; 41 42namespace { 43class VISIBILITY_HIDDEN ScalarExprEmitter 44 : public StmtVisitor<ScalarExprEmitter, Value*> { 45 CodeGenFunction &CGF; 46 CGBuilderTy &Builder; 47 48public: 49 50 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf), 51 Builder(CGF.Builder) { 52 } 53 54 //===--------------------------------------------------------------------===// 55 // Utilities 56 //===--------------------------------------------------------------------===// 57 58 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); } 59 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); } 60 61 Value *EmitLoadOfLValue(LValue LV, QualType T) { 62 return CGF.EmitLoadOfLValue(LV, T).getScalarVal(); 63 } 64 65 /// EmitLoadOfLValue - Given an expression with complex type that represents a 66 /// value l-value, this method emits the address of the l-value, then loads 67 /// and returns the result. 68 Value *EmitLoadOfLValue(const Expr *E) { 69 // FIXME: Volatile 70 return EmitLoadOfLValue(EmitLValue(E), E->getType()); 71 } 72 73 /// EmitConversionToBool - Convert the specified expression value to a 74 /// boolean (i1) truth value. This is equivalent to "Val != 0". 75 Value *EmitConversionToBool(Value *Src, QualType DstTy); 76 77 /// EmitScalarConversion - Emit a conversion from the specified type to the 78 /// specified destination type, both of which are LLVM scalar types. 79 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy); 80 81 /// EmitComplexToScalarConversion - Emit a conversion from the specified 82 /// complex type to the specified destination type, where the destination 83 /// type is an LLVM scalar type. 84 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 85 QualType SrcTy, QualType DstTy); 86 87 //===--------------------------------------------------------------------===// 88 // Visitor Methods 89 //===--------------------------------------------------------------------===// 90 91 Value *VisitStmt(Stmt *S) { 92 S->dump(CGF.getContext().getSourceManager()); 93 assert(0 && "Stmt can't have complex result type!"); 94 return 0; 95 } 96 Value *VisitExpr(Expr *S); 97 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); } 98 99 // Leaves. 100 Value *VisitIntegerLiteral(const IntegerLiteral *E) { 101 return llvm::ConstantInt::get(E->getValue()); 102 } 103 Value *VisitFloatingLiteral(const FloatingLiteral *E) { 104 return llvm::ConstantFP::get(E->getValue()); 105 } 106 Value *VisitCharacterLiteral(const CharacterLiteral *E) { 107 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 108 } 109 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 110 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()); 111 } 112 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) { 113 return llvm::Constant::getNullValue(ConvertType(E->getType())); 114 } 115 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) { 116 return llvm::ConstantInt::get(ConvertType(E->getType()), 117 CGF.getContext().typesAreCompatible( 118 E->getArgType1(), E->getArgType2())); 119 } 120 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E); 121 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) { 122 llvm::Value *V = 123 llvm::ConstantInt::get(llvm::Type::Int32Ty, 124 CGF.GetIDForAddrOfLabel(E->getLabel())); 125 126 return Builder.CreateIntToPtr(V, ConvertType(E->getType())); 127 } 128 129 // l-values. 130 Value *VisitDeclRefExpr(DeclRefExpr *E) { 131 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl())) 132 return llvm::ConstantInt::get(EC->getInitVal()); 133 return EmitLoadOfLValue(E); 134 } 135 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) { 136 return CGF.EmitObjCSelectorExpr(E); 137 } 138 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) { 139 return CGF.EmitObjCProtocolExpr(E); 140 } 141 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 142 return EmitLoadOfLValue(E); 143 } 144 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 145 return EmitLoadOfLValue(E); 146 } 147 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) { 148 return CGF.EmitObjCMessageExpr(E).getScalarVal(); 149 } 150 151 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E); 152 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E); 153 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); } 154 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); } 155 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 156 return EmitLoadOfLValue(E); 157 } 158 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); } 159 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); } 160 161 Value *VisitInitListExpr(InitListExpr *E) { 162 unsigned NumInitElements = E->getNumInits(); 163 164 const llvm::VectorType *VType = 165 dyn_cast<llvm::VectorType>(ConvertType(E->getType())); 166 167 // We have a scalar in braces. Just use the first element. 168 if (!VType) 169 return Visit(E->getInit(0)); 170 171 if (E->hadDesignators()) { 172 CGF.ErrorUnsupported(E, "initializer list with designators"); 173 return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 174 } 175 176 unsigned NumVectorElements = VType->getNumElements(); 177 const llvm::Type *ElementType = VType->getElementType(); 178 179 // Emit individual vector element stores. 180 llvm::Value *V = llvm::UndefValue::get(VType); 181 182 // Emit initializers 183 unsigned i; 184 for (i = 0; i < NumInitElements; ++i) { 185 Value *NewV = Visit(E->getInit(i)); 186 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i); 187 V = Builder.CreateInsertElement(V, NewV, Idx); 188 } 189 190 // Emit remaining default initializers 191 for (/* Do not initialize i*/; i < NumVectorElements; ++i) { 192 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i); 193 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType); 194 V = Builder.CreateInsertElement(V, NewV, Idx); 195 } 196 197 return V; 198 } 199 200 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E); 201 Value *VisitCastExpr(const CastExpr *E) { 202 return EmitCastExpr(E->getSubExpr(), E->getType()); 203 } 204 Value *EmitCastExpr(const Expr *E, QualType T); 205 206 Value *VisitCallExpr(const CallExpr *E) { 207 return CGF.EmitCallExpr(E).getScalarVal(); 208 } 209 210 Value *VisitStmtExpr(const StmtExpr *E); 211 212 // Unary Operators. 213 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre); 214 Value *VisitUnaryPostDec(const UnaryOperator *E) { 215 return VisitPrePostIncDec(E, false, false); 216 } 217 Value *VisitUnaryPostInc(const UnaryOperator *E) { 218 return VisitPrePostIncDec(E, true, false); 219 } 220 Value *VisitUnaryPreDec(const UnaryOperator *E) { 221 return VisitPrePostIncDec(E, false, true); 222 } 223 Value *VisitUnaryPreInc(const UnaryOperator *E) { 224 return VisitPrePostIncDec(E, true, true); 225 } 226 Value *VisitUnaryAddrOf(const UnaryOperator *E) { 227 return EmitLValue(E->getSubExpr()).getAddress(); 228 } 229 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); } 230 Value *VisitUnaryPlus(const UnaryOperator *E) { 231 return Visit(E->getSubExpr()); 232 } 233 Value *VisitUnaryMinus (const UnaryOperator *E); 234 Value *VisitUnaryNot (const UnaryOperator *E); 235 Value *VisitUnaryLNot (const UnaryOperator *E); 236 Value *VisitUnaryReal (const UnaryOperator *E); 237 Value *VisitUnaryImag (const UnaryOperator *E); 238 Value *VisitUnaryExtension(const UnaryOperator *E) { 239 return Visit(E->getSubExpr()); 240 } 241 Value *VisitUnaryOffsetOf(const UnaryOperator *E); 242 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 243 return Visit(DAE->getExpr()); 244 } 245 246 // Binary Operators. 247 Value *EmitMul(const BinOpInfo &Ops) { 248 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul"); 249 } 250 Value *EmitDiv(const BinOpInfo &Ops); 251 Value *EmitRem(const BinOpInfo &Ops); 252 Value *EmitAdd(const BinOpInfo &Ops); 253 Value *EmitSub(const BinOpInfo &Ops); 254 Value *EmitShl(const BinOpInfo &Ops); 255 Value *EmitShr(const BinOpInfo &Ops); 256 Value *EmitAnd(const BinOpInfo &Ops) { 257 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and"); 258 } 259 Value *EmitXor(const BinOpInfo &Ops) { 260 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor"); 261 } 262 Value *EmitOr (const BinOpInfo &Ops) { 263 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or"); 264 } 265 266 BinOpInfo EmitBinOps(const BinaryOperator *E); 267 Value *EmitCompoundAssign(const CompoundAssignOperator *E, 268 Value *(ScalarExprEmitter::*F)(const BinOpInfo &)); 269 270 // Binary operators and binary compound assignment operators. 271#define HANDLEBINOP(OP) \ 272 Value *VisitBin ## OP(const BinaryOperator *E) { \ 273 return Emit ## OP(EmitBinOps(E)); \ 274 } \ 275 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \ 276 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \ 277 } 278 HANDLEBINOP(Mul); 279 HANDLEBINOP(Div); 280 HANDLEBINOP(Rem); 281 HANDLEBINOP(Add); 282 HANDLEBINOP(Sub); 283 HANDLEBINOP(Shl); 284 HANDLEBINOP(Shr); 285 HANDLEBINOP(And); 286 HANDLEBINOP(Xor); 287 HANDLEBINOP(Or); 288#undef HANDLEBINOP 289 290 // Comparisons. 291 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc, 292 unsigned SICmpOpc, unsigned FCmpOpc); 293#define VISITCOMP(CODE, UI, SI, FP) \ 294 Value *VisitBin##CODE(const BinaryOperator *E) { \ 295 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \ 296 llvm::FCmpInst::FP); } 297 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT); 298 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT); 299 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE); 300 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE); 301 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ); 302 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE); 303#undef VISITCOMP 304 305 Value *VisitBinAssign (const BinaryOperator *E); 306 307 Value *VisitBinLAnd (const BinaryOperator *E); 308 Value *VisitBinLOr (const BinaryOperator *E); 309 Value *VisitBinComma (const BinaryOperator *E); 310 311 // Other Operators. 312 Value *VisitConditionalOperator(const ConditionalOperator *CO); 313 Value *VisitChooseExpr(ChooseExpr *CE); 314 Value *VisitOverloadExpr(OverloadExpr *OE); 315 Value *VisitVAArgExpr(VAArgExpr *VE); 316 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) { 317 return CGF.EmitObjCStringLiteral(E); 318 } 319 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E); 320}; 321} // end anonymous namespace. 322 323//===----------------------------------------------------------------------===// 324// Utilities 325//===----------------------------------------------------------------------===// 326 327/// EmitConversionToBool - Convert the specified expression value to a 328/// boolean (i1) truth value. This is equivalent to "Val != 0". 329Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) { 330 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs"); 331 332 if (SrcType->isRealFloatingType()) { 333 // Compare against 0.0 for fp scalars. 334 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType()); 335 return Builder.CreateFCmpUNE(Src, Zero, "tobool"); 336 } 337 338 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) && 339 "Unknown scalar type to convert"); 340 341 // Because of the type rules of C, we often end up computing a logical value, 342 // then zero extending it to int, then wanting it as a logical value again. 343 // Optimize this common case. 344 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) { 345 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) { 346 Value *Result = ZI->getOperand(0); 347 // If there aren't any more uses, zap the instruction to save space. 348 // Note that there can be more uses, for example if this 349 // is the result of an assignment. 350 if (ZI->use_empty()) 351 ZI->eraseFromParent(); 352 return Result; 353 } 354 } 355 356 // Compare against an integer or pointer null. 357 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType()); 358 return Builder.CreateICmpNE(Src, Zero, "tobool"); 359} 360 361/// EmitScalarConversion - Emit a conversion from the specified type to the 362/// specified destination type, both of which are LLVM scalar types. 363Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType, 364 QualType DstType) { 365 SrcType = CGF.getContext().getCanonicalType(SrcType); 366 DstType = CGF.getContext().getCanonicalType(DstType); 367 if (SrcType == DstType) return Src; 368 369 if (DstType->isVoidType()) return 0; 370 371 // Handle conversions to bool first, they are special: comparisons against 0. 372 if (DstType->isBooleanType()) 373 return EmitConversionToBool(Src, SrcType); 374 375 const llvm::Type *DstTy = ConvertType(DstType); 376 377 // Ignore conversions like int -> uint. 378 if (Src->getType() == DstTy) 379 return Src; 380 381 // Handle pointer conversions next: pointers can only be converted 382 // to/from other pointers and integers. Check for pointer types in 383 // terms of LLVM, as some native types (like Obj-C id) may map to a 384 // pointer type. 385 if (isa<llvm::PointerType>(DstTy)) { 386 // The source value may be an integer, or a pointer. 387 if (isa<llvm::PointerType>(Src->getType())) 388 return Builder.CreateBitCast(Src, DstTy, "conv"); 389 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?"); 390 return Builder.CreateIntToPtr(Src, DstTy, "conv"); 391 } 392 393 if (isa<llvm::PointerType>(Src->getType())) { 394 // Must be an ptr to int cast. 395 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?"); 396 return Builder.CreatePtrToInt(Src, DstTy, "conv"); 397 } 398 399 // A scalar can be splatted to an extended vector of the same element type 400 if (DstType->isExtVectorType() && !isa<VectorType>(SrcType) && 401 cast<llvm::VectorType>(DstTy)->getElementType() == Src->getType()) 402 return CGF.EmitVector(&Src, DstType->getAsVectorType()->getNumElements(), 403 true); 404 405 // Allow bitcast from vector to integer/fp of the same size. 406 if (isa<llvm::VectorType>(Src->getType()) || 407 isa<llvm::VectorType>(DstTy)) 408 return Builder.CreateBitCast(Src, DstTy, "conv"); 409 410 // Finally, we have the arithmetic types: real int/float. 411 if (isa<llvm::IntegerType>(Src->getType())) { 412 bool InputSigned = SrcType->isSignedIntegerType(); 413 if (isa<llvm::IntegerType>(DstTy)) 414 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv"); 415 else if (InputSigned) 416 return Builder.CreateSIToFP(Src, DstTy, "conv"); 417 else 418 return Builder.CreateUIToFP(Src, DstTy, "conv"); 419 } 420 421 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion"); 422 if (isa<llvm::IntegerType>(DstTy)) { 423 if (DstType->isSignedIntegerType()) 424 return Builder.CreateFPToSI(Src, DstTy, "conv"); 425 else 426 return Builder.CreateFPToUI(Src, DstTy, "conv"); 427 } 428 429 assert(DstTy->isFloatingPoint() && "Unknown real conversion"); 430 if (DstTy->getTypeID() < Src->getType()->getTypeID()) 431 return Builder.CreateFPTrunc(Src, DstTy, "conv"); 432 else 433 return Builder.CreateFPExt(Src, DstTy, "conv"); 434} 435 436/// EmitComplexToScalarConversion - Emit a conversion from the specified 437/// complex type to the specified destination type, where the destination 438/// type is an LLVM scalar type. 439Value *ScalarExprEmitter:: 440EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src, 441 QualType SrcTy, QualType DstTy) { 442 // Get the source element type. 443 SrcTy = SrcTy->getAsComplexType()->getElementType(); 444 445 // Handle conversions to bool first, they are special: comparisons against 0. 446 if (DstTy->isBooleanType()) { 447 // Complex != 0 -> (Real != 0) | (Imag != 0) 448 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy); 449 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy); 450 return Builder.CreateOr(Src.first, Src.second, "tobool"); 451 } 452 453 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type, 454 // the imaginary part of the complex value is discarded and the value of the 455 // real part is converted according to the conversion rules for the 456 // corresponding real type. 457 return EmitScalarConversion(Src.first, SrcTy, DstTy); 458} 459 460 461//===----------------------------------------------------------------------===// 462// Visitor Methods 463//===----------------------------------------------------------------------===// 464 465Value *ScalarExprEmitter::VisitExpr(Expr *E) { 466 CGF.ErrorUnsupported(E, "scalar expression"); 467 if (E->getType()->isVoidType()) 468 return 0; 469 return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 470} 471 472Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { 473 llvm::SmallVector<llvm::Constant*, 32> indices; 474 for (unsigned i = 2; i < E->getNumSubExprs(); i++) { 475 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i)))); 476 } 477 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0)); 478 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1)); 479 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size()); 480 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle"); 481} 482 483Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 484 // Emit subscript expressions in rvalue context's. For most cases, this just 485 // loads the lvalue formed by the subscript expr. However, we have to be 486 // careful, because the base of a vector subscript is occasionally an rvalue, 487 // so we can't get it as an lvalue. 488 if (!E->getBase()->getType()->isVectorType()) 489 return EmitLoadOfLValue(E); 490 491 // Handle the vector case. The base must be a vector, the index must be an 492 // integer value. 493 Value *Base = Visit(E->getBase()); 494 Value *Idx = Visit(E->getIdx()); 495 496 // FIXME: Convert Idx to i32 type. 497 return Builder.CreateExtractElement(Base, Idx, "vecext"); 498} 499 500/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but 501/// also handle things like function to pointer-to-function decay, and array to 502/// pointer decay. 503Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) { 504 const Expr *Op = E->getSubExpr(); 505 506 // If this is due to array->pointer conversion, emit the array expression as 507 // an l-value. 508 if (Op->getType()->isArrayType()) { 509 // FIXME: For now we assume that all source arrays map to LLVM arrays. This 510 // will not true when we add support for VLAs. 511 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays. 512 513 if (!(isa<llvm::PointerType>(V->getType()) && 514 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType()) 515 ->getElementType()))) { 516 CGF.ErrorUnsupported(E, "variable-length array cast", true); 517 if (E->getType()->isVoidType()) 518 return 0; 519 return llvm::UndefValue::get(CGF.ConvertType(E->getType())); 520 } 521 V = Builder.CreateStructGEP(V, 0, "arraydecay"); 522 523 // The resultant pointer type can be implicitly casted to other pointer 524 // types as well (e.g. void*) and can be implicitly converted to integer. 525 const llvm::Type *DestTy = ConvertType(E->getType()); 526 if (V->getType() != DestTy) { 527 if (isa<llvm::PointerType>(DestTy)) 528 V = Builder.CreateBitCast(V, DestTy, "ptrconv"); 529 else { 530 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay"); 531 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv"); 532 } 533 } 534 return V; 535 536 } else if (E->getType()->isReferenceType()) { 537 return EmitLValue(Op).getAddress(); 538 } 539 540 return EmitCastExpr(Op, E->getType()); 541} 542 543 544// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts 545// have to handle a more broad range of conversions than explicit casts, as they 546// handle things like function to ptr-to-function decay etc. 547Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) { 548 // Handle cases where the source is an non-complex type. 549 550 if (!CGF.hasAggregateLLVMType(E->getType())) { 551 Value *Src = Visit(const_cast<Expr*>(E)); 552 553 // Use EmitScalarConversion to perform the conversion. 554 return EmitScalarConversion(Src, E->getType(), DestTy); 555 } 556 557 if (E->getType()->isAnyComplexType()) { 558 // Handle cases where the source is a complex type. 559 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(), 560 DestTy); 561 } 562 563 // Okay, this is a cast from an aggregate. It must be a cast to void. Just 564 // evaluate the result and return. 565 CGF.EmitAggExpr(E, 0, false); 566 return 0; 567} 568 569Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) { 570 return CGF.EmitCompoundStmt(*E->getSubStmt(), 571 !E->getType()->isVoidType()).getScalarVal(); 572} 573 574 575//===----------------------------------------------------------------------===// 576// Unary Operators 577//===----------------------------------------------------------------------===// 578 579Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E, 580 bool isInc, bool isPre) { 581 LValue LV = EmitLValue(E->getSubExpr()); 582 // FIXME: Handle volatile! 583 Value *InVal = CGF.EmitLoadOfLValue(LV, // false 584 E->getSubExpr()->getType()).getScalarVal(); 585 586 int AmountVal = isInc ? 1 : -1; 587 588 Value *NextVal; 589 if (isa<llvm::PointerType>(InVal->getType())) { 590 // FIXME: This isn't right for VLAs. 591 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal); 592 NextVal = Builder.CreateGEP(InVal, NextVal, "ptrincdec"); 593 } else { 594 // Add the inc/dec to the real part. 595 if (isa<llvm::IntegerType>(InVal->getType())) 596 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal); 597 else if (InVal->getType() == llvm::Type::FloatTy) 598 NextVal = 599 llvm::ConstantFP::get(llvm::APFloat(static_cast<float>(AmountVal))); 600 else if (InVal->getType() == llvm::Type::DoubleTy) 601 NextVal = 602 llvm::ConstantFP::get(llvm::APFloat(static_cast<double>(AmountVal))); 603 else { 604 llvm::APFloat F(static_cast<float>(AmountVal)); 605 bool ignored; 606 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero, 607 &ignored); 608 NextVal = llvm::ConstantFP::get(F); 609 } 610 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec"); 611 } 612 613 // Store the updated result through the lvalue. 614 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, 615 E->getSubExpr()->getType()); 616 617 // If this is a postinc, return the value read from memory, otherwise use the 618 // updated value. 619 return isPre ? NextVal : InVal; 620} 621 622 623Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) { 624 Value *Op = Visit(E->getSubExpr()); 625 return Builder.CreateNeg(Op, "neg"); 626} 627 628Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) { 629 Value *Op = Visit(E->getSubExpr()); 630 return Builder.CreateNot(Op, "neg"); 631} 632 633Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) { 634 // Compare operand to zero. 635 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr()); 636 637 // Invert value. 638 // TODO: Could dynamically modify easy computations here. For example, if 639 // the operand is an icmp ne, turn into icmp eq. 640 BoolVal = Builder.CreateNot(BoolVal, "lnot"); 641 642 // ZExt result to int. 643 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext"); 644} 645 646/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of 647/// argument of the sizeof expression as an integer. 648Value * 649ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) { 650 QualType RetType = E->getType(); 651 assert(RetType->isIntegerType() && "Result type must be an integer!"); 652 uint32_t ResultWidth = 653 static_cast<uint32_t>(CGF.getContext().getTypeSize(RetType)); 654 655 QualType TypeToSize = E->getTypeOfArgument(); 656 // sizeof(void) and __alignof__(void) = 1 as a gcc extension. Also 657 // for function types. 658 // FIXME: what is alignof a function type in gcc? 659 if (TypeToSize->isVoidType() || TypeToSize->isFunctionType()) 660 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, 1)); 661 662 /// FIXME: This doesn't handle VLAs yet! 663 std::pair<uint64_t, unsigned> Info = CGF.getContext().getTypeInfo(TypeToSize); 664 665 uint64_t Val = E->isSizeOf() ? Info.first : Info.second; 666 Val /= 8; // Return size in bytes, not bits. 667 668 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val)); 669} 670 671Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) { 672 Expr *Op = E->getSubExpr(); 673 if (Op->getType()->isAnyComplexType()) 674 return CGF.EmitComplexExpr(Op).first; 675 return Visit(Op); 676} 677Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) { 678 Expr *Op = E->getSubExpr(); 679 if (Op->getType()->isAnyComplexType()) 680 return CGF.EmitComplexExpr(Op).second; 681 682 // __imag on a scalar returns zero. Emit it the subexpr to ensure side 683 // effects are evaluated. 684 CGF.EmitScalarExpr(Op); 685 return llvm::Constant::getNullValue(ConvertType(E->getType())); 686} 687 688Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E) 689{ 690 int64_t Val = E->evaluateOffsetOf(CGF.getContext()); 691 692 assert(E->getType()->isIntegerType() && "Result type must be an integer!"); 693 694 uint32_t ResultWidth = 695 static_cast<uint32_t>(CGF.getContext().getTypeSize(E->getType())); 696 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val)); 697} 698 699//===----------------------------------------------------------------------===// 700// Binary Operators 701//===----------------------------------------------------------------------===// 702 703BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) { 704 BinOpInfo Result; 705 Result.LHS = Visit(E->getLHS()); 706 Result.RHS = Visit(E->getRHS()); 707 Result.Ty = E->getType(); 708 Result.E = E; 709 return Result; 710} 711 712Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E, 713 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) { 714 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType(); 715 716 BinOpInfo OpInfo; 717 718 // Load the LHS and RHS operands. 719 LValue LHSLV = EmitLValue(E->getLHS()); 720 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy); 721 722 // Determine the computation type. If the RHS is complex, then this is one of 723 // the add/sub/mul/div operators. All of these operators can be computed in 724 // with just their real component even though the computation domain really is 725 // complex. 726 QualType ComputeType = E->getComputationType(); 727 728 // If the computation type is complex, then the RHS is complex. Emit the RHS. 729 if (const ComplexType *CT = ComputeType->getAsComplexType()) { 730 ComputeType = CT->getElementType(); 731 732 // Emit the RHS, only keeping the real component. 733 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first; 734 RHSTy = RHSTy->getAsComplexType()->getElementType(); 735 } else { 736 // Otherwise the RHS is a simple scalar value. 737 OpInfo.RHS = Visit(E->getRHS()); 738 } 739 740 QualType LComputeTy, RComputeTy, ResultTy; 741 742 // Compound assignment does not contain enough information about all 743 // the types involved for pointer arithmetic cases. Figure it out 744 // here for now. 745 if (E->getLHS()->getType()->isPointerType()) { 746 // Pointer arithmetic cases: ptr +=,-= int and ptr -= ptr, 747 assert((E->getOpcode() == BinaryOperator::AddAssign || 748 E->getOpcode() == BinaryOperator::SubAssign) && 749 "Invalid compound assignment operator on pointer type."); 750 LComputeTy = E->getLHS()->getType(); 751 752 if (E->getRHS()->getType()->isPointerType()) { 753 // Degenerate case of (ptr -= ptr) allowed by GCC implicit cast 754 // extension, the conversion from the pointer difference back to 755 // the LHS type is handled at the end. 756 assert(E->getOpcode() == BinaryOperator::SubAssign && 757 "Invalid compound assignment operator on pointer type."); 758 RComputeTy = E->getLHS()->getType(); 759 ResultTy = CGF.getContext().getPointerDiffType(); 760 } else { 761 RComputeTy = E->getRHS()->getType(); 762 ResultTy = LComputeTy; 763 } 764 } else if (E->getRHS()->getType()->isPointerType()) { 765 // Degenerate case of (int += ptr) allowed by GCC implicit cast 766 // extension. 767 assert(E->getOpcode() == BinaryOperator::AddAssign && 768 "Invalid compound assignment operator on pointer type."); 769 LComputeTy = E->getLHS()->getType(); 770 RComputeTy = E->getRHS()->getType(); 771 ResultTy = RComputeTy; 772 } else { 773 LComputeTy = RComputeTy = ResultTy = ComputeType; 774 } 775 776 // Convert the LHS/RHS values to the computation type. 777 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, LComputeTy); 778 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, RComputeTy); 779 OpInfo.Ty = ResultTy; 780 OpInfo.E = E; 781 782 // Expand the binary operator. 783 Value *Result = (this->*Func)(OpInfo); 784 785 // Convert the result back to the LHS type. 786 Result = EmitScalarConversion(Result, ResultTy, LHSTy); 787 788 // Store the result value into the LHS lvalue. 789 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy); 790 791 // For bitfields, we need the value in the bitfield. Note that 792 // property references do not reload their value (even though the 793 // setter may have changed it). 794 // FIXME: This adds an extra bitfield load 795 if (LHSLV.isBitfield()) 796 Result = EmitLoadOfLValue(LHSLV, LHSTy); 797 return Result; 798} 799 800 801Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) { 802 if (Ops.LHS->getType()->isFPOrFPVector()) 803 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div"); 804 else if (Ops.Ty->isUnsignedIntegerType()) 805 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div"); 806 else 807 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div"); 808} 809 810Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) { 811 // Rem in C can't be a floating point type: C99 6.5.5p2. 812 if (Ops.Ty->isUnsignedIntegerType()) 813 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem"); 814 else 815 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem"); 816} 817 818 819Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) { 820 if (!Ops.Ty->isPointerType()) 821 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add"); 822 823 // FIXME: What about a pointer to a VLA? 824 Value *Ptr, *Idx; 825 Expr *IdxExp; 826 if (isa<llvm::PointerType>(Ops.LHS->getType())) { // pointer + int 827 Ptr = Ops.LHS; 828 Idx = Ops.RHS; 829 IdxExp = Ops.E->getRHS(); 830 } else { // int + pointer 831 Ptr = Ops.RHS; 832 Idx = Ops.LHS; 833 IdxExp = Ops.E->getLHS(); 834 } 835 836 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); 837 if (Width < CGF.LLVMPointerWidth) { 838 // Zero or sign extend the pointer value based on whether the index is 839 // signed or not. 840 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth); 841 if (IdxExp->getType()->isSignedIntegerType()) 842 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext"); 843 else 844 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext"); 845 } 846 847 return Builder.CreateGEP(Ptr, Idx, "add.ptr"); 848} 849 850Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) { 851 if (!isa<llvm::PointerType>(Ops.LHS->getType())) 852 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub"); 853 854 if (!isa<llvm::PointerType>(Ops.RHS->getType())) { 855 // pointer - int 856 Value *Idx = Ops.RHS; 857 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); 858 if (Width < CGF.LLVMPointerWidth) { 859 // Zero or sign extend the pointer value based on whether the index is 860 // signed or not. 861 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth); 862 if (Ops.E->getRHS()->getType()->isSignedIntegerType()) 863 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext"); 864 else 865 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext"); 866 } 867 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg"); 868 869 // FIXME: The pointer could point to a VLA. 870 // The GNU void* - int case is automatically handled here because 871 // our LLVM type for void* is i8*. 872 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr"); 873 } else { 874 // pointer - pointer 875 Value *LHS = Ops.LHS; 876 Value *RHS = Ops.RHS; 877 878 const QualType LHSType = Ops.E->getLHS()->getType(); 879 const QualType LHSElementType = LHSType->getAsPointerType()->getPointeeType(); 880 uint64_t ElementSize; 881 882 // Handle GCC extension for pointer arithmetic on void* types. 883 if (LHSElementType->isVoidType()) { 884 ElementSize = 1; 885 } else { 886 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8; 887 } 888 889 const llvm::Type *ResultType = ConvertType(Ops.Ty); 890 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast"); 891 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast"); 892 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub"); 893 894 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no 895 // remainder. As such, we handle common power-of-two cases here to generate 896 // better code. See PR2247. 897 if (llvm::isPowerOf2_64(ElementSize)) { 898 Value *ShAmt = 899 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize)); 900 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr"); 901 } 902 903 // Otherwise, do a full sdiv. 904 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize); 905 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div"); 906 } 907} 908 909Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) { 910 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 911 // RHS to the same size as the LHS. 912 Value *RHS = Ops.RHS; 913 if (Ops.LHS->getType() != RHS->getType()) 914 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 915 916 return Builder.CreateShl(Ops.LHS, RHS, "shl"); 917} 918 919Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) { 920 // LLVM requires the LHS and RHS to be the same type: promote or truncate the 921 // RHS to the same size as the LHS. 922 Value *RHS = Ops.RHS; 923 if (Ops.LHS->getType() != RHS->getType()) 924 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom"); 925 926 if (Ops.Ty->isUnsignedIntegerType()) 927 return Builder.CreateLShr(Ops.LHS, RHS, "shr"); 928 return Builder.CreateAShr(Ops.LHS, RHS, "shr"); 929} 930 931Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc, 932 unsigned SICmpOpc, unsigned FCmpOpc) { 933 Value *Result; 934 QualType LHSTy = E->getLHS()->getType(); 935 if (!LHSTy->isAnyComplexType() && !LHSTy->isVectorType()) { 936 Value *LHS = Visit(E->getLHS()); 937 Value *RHS = Visit(E->getRHS()); 938 939 if (LHS->getType()->isFloatingPoint()) { 940 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc, 941 LHS, RHS, "cmp"); 942 } else if (LHSTy->isSignedIntegerType()) { 943 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc, 944 LHS, RHS, "cmp"); 945 } else { 946 // Unsigned integers and pointers. 947 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 948 LHS, RHS, "cmp"); 949 } 950 } else if (LHSTy->isVectorType()) { 951 Value *LHS = Visit(E->getLHS()); 952 Value *RHS = Visit(E->getRHS()); 953 954 if (LHS->getType()->isFPOrFPVector()) { 955 Result = Builder.CreateVFCmp((llvm::CmpInst::Predicate)FCmpOpc, 956 LHS, RHS, "cmp"); 957 } else if (LHSTy->isUnsignedIntegerType()) { 958 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)UICmpOpc, 959 LHS, RHS, "cmp"); 960 } else { 961 // Signed integers and pointers. 962 Result = Builder.CreateVICmp((llvm::CmpInst::Predicate)SICmpOpc, 963 LHS, RHS, "cmp"); 964 } 965 return Result; 966 } else { 967 // Complex Comparison: can only be an equality comparison. 968 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS()); 969 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS()); 970 971 QualType CETy = LHSTy->getAsComplexType()->getElementType(); 972 973 Value *ResultR, *ResultI; 974 if (CETy->isRealFloatingType()) { 975 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 976 LHS.first, RHS.first, "cmp.r"); 977 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc, 978 LHS.second, RHS.second, "cmp.i"); 979 } else { 980 // Complex comparisons can only be equality comparisons. As such, signed 981 // and unsigned opcodes are the same. 982 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 983 LHS.first, RHS.first, "cmp.r"); 984 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc, 985 LHS.second, RHS.second, "cmp.i"); 986 } 987 988 if (E->getOpcode() == BinaryOperator::EQ) { 989 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri"); 990 } else { 991 assert(E->getOpcode() == BinaryOperator::NE && 992 "Complex comparison other than == or != ?"); 993 Result = Builder.CreateOr(ResultR, ResultI, "or.ri"); 994 } 995 } 996 997 // ZExt result to int. 998 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext"); 999} 1000 1001Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) { 1002 LValue LHS = EmitLValue(E->getLHS()); 1003 Value *RHS = Visit(E->getRHS()); 1004 1005 // Store the value into the LHS. 1006 // FIXME: Volatility! 1007 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType()); 1008 1009 // For bitfields, we need the value in the bitfield. Note that 1010 // property references do not reload their value (even though the 1011 // setter may have changed it). 1012 // FIXME: This adds an extra bitfield load 1013 if (LHS.isBitfield()) 1014 return EmitLoadOfLValue(LHS, E->getLHS()->getType()); 1015 1016 // Return the RHS. 1017 return RHS; 1018} 1019 1020Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) { 1021 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS()); 1022 1023 if (llvm::ConstantInt *LHSCst = dyn_cast<llvm::ConstantInt>(LHSCond)) { 1024 // If we have 0 && RHS, see if we can elide RHS, if so, just return LHSCond. 1025 if (LHSCst->isZero()) { 1026 if (!CGF.ContainsLabel(E->getRHS())) 1027 // Elide RHS, return 0 1028 return llvm::Constant::getNullValue(CGF.LLVMIntTy); 1029 } else { 1030 // If we have 1 && X, just emit X without inserting the control flow. 1031 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1032 // ZExt result to int. 1033 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext"); 1034 } 1035 } 1036 1037 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land_cont"); 1038 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land_rhs"); 1039 1040 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock(); 1041 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock); 1042 1043 CGF.EmitBlock(RHSBlock); 1044 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1045 1046 // Reaquire the RHS block, as there may be subblocks inserted. 1047 RHSBlock = Builder.GetInsertBlock(); 1048 CGF.EmitBlock(ContBlock); 1049 1050 // Create a PHI node. If we just evaluted the LHS condition, the result is 1051 // false. If we evaluated both, the result is the RHS condition. 1052 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land"); 1053 PN->reserveOperandSpace(2); 1054 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock); 1055 PN->addIncoming(RHSCond, RHSBlock); 1056 1057 // ZExt result to int. 1058 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext"); 1059} 1060 1061Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) { 1062 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS()); 1063 1064 if (llvm::ConstantInt *LHSCst = dyn_cast<llvm::ConstantInt>(LHSCond)) { 1065 // If we have 1 || RHS, see if we can elide RHS, if so, just return LHSCond. 1066 if (!LHSCst->isZero()) { 1067 if (!CGF.ContainsLabel(E->getRHS())) 1068 // Elide RHS, return 1 1069 return llvm::ConstantInt::get(CGF.LLVMIntTy, 1); 1070 } else { 1071 // If we have 0 || X, just emit X without inserting the control flow. 1072 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1073 // ZExt result to int. 1074 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext"); 1075 } 1076 } 1077 1078 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor_cont"); 1079 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor_rhs"); 1080 1081 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock(); 1082 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock); 1083 1084 CGF.EmitBlock(RHSBlock); 1085 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS()); 1086 1087 // Reaquire the RHS block, as there may be subblocks inserted. 1088 RHSBlock = Builder.GetInsertBlock(); 1089 CGF.EmitBlock(ContBlock); 1090 1091 // Create a PHI node. If we just evaluted the LHS condition, the result is 1092 // true. If we evaluated both, the result is the RHS condition. 1093 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor"); 1094 PN->reserveOperandSpace(2); 1095 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock); 1096 PN->addIncoming(RHSCond, RHSBlock); 1097 1098 // ZExt result to int. 1099 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext"); 1100} 1101 1102Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) { 1103 CGF.EmitStmt(E->getLHS()); 1104 CGF.EnsureInsertPoint(); 1105 return Visit(E->getRHS()); 1106} 1107 1108//===----------------------------------------------------------------------===// 1109// Other Operators 1110//===----------------------------------------------------------------------===// 1111 1112Value *ScalarExprEmitter:: 1113VisitConditionalOperator(const ConditionalOperator *E) { 1114 // If the condition constant folds and can be elided, try to avoid emitting 1115 // the condition and the dead arm. 1116 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){ 1117 Expr *Live = E->getLHS(), *Dead = E->getRHS(); 1118 if (Cond == -1) 1119 std::swap(Live, Dead); 1120 1121 // If the dead side doesn't have labels we need, and if the Live side isn't 1122 // the gnu missing ?: extension (which we could handle, but don't bother 1123 // to), just emit the Live part. 1124 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part 1125 Live) // Live part isn't missing. 1126 return Visit(Live); 1127 } 1128 1129 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.?"); 1130 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.:"); 1131 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.cont"); 1132 1133 // Evaluate the conditional, then convert it to bool. We do this explicitly 1134 // because we need the unconverted value if this is a GNU ?: expression with 1135 // missing middle value. 1136 Value *CondVal = CGF.EmitScalarExpr(E->getCond()); 1137 Value *CondBoolVal =CGF.EmitScalarConversion(CondVal, E->getCond()->getType(), 1138 CGF.getContext().BoolTy); 1139 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock); 1140 1141 CGF.EmitBlock(LHSBlock); 1142 1143 // Handle the GNU extension for missing LHS. 1144 Value *LHS; 1145 if (E->getLHS()) 1146 LHS = Visit(E->getLHS()); 1147 else // Perform promotions, to handle cases like "short ?: int" 1148 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType()); 1149 1150 LHSBlock = Builder.GetInsertBlock(); 1151 CGF.EmitBranch(ContBlock); 1152 1153 CGF.EmitBlock(RHSBlock); 1154 1155 Value *RHS = Visit(E->getRHS()); 1156 RHSBlock = Builder.GetInsertBlock(); 1157 CGF.EmitBranch(ContBlock); 1158 1159 CGF.EmitBlock(ContBlock); 1160 1161 if (!LHS || !RHS) { 1162 assert(E->getType()->isVoidType() && "Non-void value should have a value"); 1163 return 0; 1164 } 1165 1166 // Create a PHI node for the real part. 1167 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond"); 1168 PN->reserveOperandSpace(2); 1169 PN->addIncoming(LHS, LHSBlock); 1170 PN->addIncoming(RHS, RHSBlock); 1171 return PN; 1172} 1173 1174Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) { 1175 // Emit the LHS or RHS as appropriate. 1176 return 1177 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS()); 1178} 1179 1180Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) { 1181 return CGF.EmitCallExpr(E->getFn(), E->arg_begin(), 1182 E->arg_end(CGF.getContext())).getScalarVal(); 1183} 1184 1185Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 1186 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress(); 1187 1188 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 1189 1190 // If EmitVAArg fails, we fall back to the LLVM instruction. 1191 if (!ArgPtr) 1192 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType())); 1193 1194 // FIXME: volatile? 1195 return Builder.CreateLoad(ArgPtr); 1196} 1197 1198Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { 1199 std::string str; 1200 CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str); 1201 1202 llvm::Constant *C = llvm::ConstantArray::get(str); 1203 C = new llvm::GlobalVariable(C->getType(), true, 1204 llvm::GlobalValue::InternalLinkage, 1205 C, ".str", &CGF.CGM.getModule()); 1206 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty); 1207 llvm::Constant *Zeros[] = { Zero, Zero }; 1208 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2); 1209 1210 return C; 1211} 1212 1213//===----------------------------------------------------------------------===// 1214// Entry Point into this File 1215//===----------------------------------------------------------------------===// 1216 1217/// EmitComplexExpr - Emit the computation of the specified expression of 1218/// complex type, ignoring the result. 1219Value *CodeGenFunction::EmitScalarExpr(const Expr *E) { 1220 assert(E && !hasAggregateLLVMType(E->getType()) && 1221 "Invalid scalar expression to emit"); 1222 1223 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E)); 1224} 1225 1226/// EmitScalarConversion - Emit a conversion from the specified type to the 1227/// specified destination type, both of which are LLVM scalar types. 1228Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy, 1229 QualType DstTy) { 1230 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) && 1231 "Invalid scalar expression to emit"); 1232 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy); 1233} 1234 1235/// EmitComplexToScalarConversion - Emit a conversion from the specified 1236/// complex type to the specified destination type, where the destination 1237/// type is an LLVM scalar type. 1238Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src, 1239 QualType SrcTy, 1240 QualType DstTy) { 1241 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) && 1242 "Invalid complex -> scalar conversion"); 1243 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy, 1244 DstTy); 1245} 1246 1247Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) { 1248 assert(V1->getType() == V2->getType() && 1249 "Vector operands must be of the same type"); 1250 unsigned NumElements = 1251 cast<llvm::VectorType>(V1->getType())->getNumElements(); 1252 1253 va_list va; 1254 va_start(va, V2); 1255 1256 llvm::SmallVector<llvm::Constant*, 16> Args; 1257 for (unsigned i = 0; i < NumElements; i++) { 1258 int n = va_arg(va, int); 1259 assert(n >= 0 && n < (int)NumElements * 2 && 1260 "Vector shuffle index out of bounds!"); 1261 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n)); 1262 } 1263 1264 const char *Name = va_arg(va, const char *); 1265 va_end(va); 1266 1267 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements); 1268 1269 return Builder.CreateShuffleVector(V1, V2, Mask, Name); 1270} 1271 1272llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals, 1273 unsigned NumVals, bool isSplat) { 1274 llvm::Value *Vec 1275 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals)); 1276 1277 for (unsigned i = 0, e = NumVals; i != e; ++i) { 1278 llvm::Value *Val = isSplat ? Vals[0] : Vals[i]; 1279 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i); 1280 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp"); 1281 } 1282 1283 return Vec; 1284} 1285