1 //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===// 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 as LLVM code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CodeGenModule.h" 16 #include "CGCall.h" 17 #include "CGObjCRuntime.h" 18 #include "clang/AST/ASTContext.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "llvm/Target/TargetData.h" 21 using namespace clang; 22 using namespace CodeGen; 23 24 //===--------------------------------------------------------------------===// 25 // Miscellaneous Helper Methods 26 //===--------------------------------------------------------------------===// 27 28 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 29 /// block. 30 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty, 31 const char *Name) { 32 if (!Builder.isNamePreserving()) 33 Name = ""; 34 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt); 35 } 36 37 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 38 /// expression and compare the result against zero, returning an Int1Ty value. 39 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) { 40 QualType BoolTy = getContext().BoolTy; 41 if (!E->getType()->isAnyComplexType()) 42 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy); 43 44 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy); 45 } 46 47 /// EmitAnyExpr - Emit code to compute the specified expression which can have 48 /// any type. The result is returned as an RValue struct. If this is an 49 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 50 /// the result should be returned. 51 RValue CodeGenFunction::EmitAnyExpr(const Expr *E, llvm::Value *AggLoc, 52 bool IsAggLocVolatile, bool IgnoreResult, 53 bool IsInitializer) { 54 if (!hasAggregateLLVMType(E->getType())) 55 return RValue::get(EmitScalarExpr(E, IgnoreResult)); 56 else if (E->getType()->isAnyComplexType()) 57 return RValue::getComplex(EmitComplexExpr(E, false, false, 58 IgnoreResult, IgnoreResult)); 59 60 EmitAggExpr(E, AggLoc, IsAggLocVolatile, IgnoreResult, IsInitializer); 61 return RValue::getAggregate(AggLoc, IsAggLocVolatile); 62 } 63 64 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result 65 /// will always be accessible even if no aggregate location is 66 /// provided. 67 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E, 68 bool IsAggLocVolatile, 69 bool IsInitializer) { 70 llvm::Value *AggLoc = 0; 71 72 if (hasAggregateLLVMType(E->getType()) && 73 !E->getType()->isAnyComplexType()) 74 AggLoc = CreateTempAlloca(ConvertType(E->getType()), "agg.tmp"); 75 return EmitAnyExpr(E, AggLoc, IsAggLocVolatile, /*IgnoreResult=*/false, 76 IsInitializer); 77 } 78 79 RValue CodeGenFunction::EmitReferenceBindingToExpr(const Expr* E, 80 QualType DestType, 81 bool IsInitializer) { 82 RValue Val; 83 if (E->isLvalue(getContext()) == Expr::LV_Valid) { 84 // Emit the expr as an lvalue. 85 LValue LV = EmitLValue(E); 86 if (LV.isSimple()) 87 return RValue::get(LV.getAddress()); 88 Val = EmitLoadOfLValue(LV, E->getType()); 89 } else { 90 // FIXME: Initializers don't work with casts yet. For example 91 // const A& a = B(); 92 // if B inherits from A. 93 Val = EmitAnyExprToTemp(E, /*IsAggLocVolatile=*/false, 94 IsInitializer); 95 96 if (IsInitializer) { 97 // We might have to destroy the temporary variable. 98 if (const RecordType *RT = E->getType()->getAs<RecordType>()) { 99 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 100 if (!ClassDecl->hasTrivialDestructor()) { 101 const CXXDestructorDecl *Dtor = 102 ClassDecl->getDestructor(getContext()); 103 104 CleanupScope scope(*this); 105 EmitCXXDestructorCall(Dtor, Dtor_Complete, Val.getAggregateAddr()); 106 } 107 } 108 } 109 } 110 } 111 112 if (Val.isAggregate()) { 113 Val = RValue::get(Val.getAggregateAddr()); 114 } else { 115 // Create a temporary variable that we can bind the reference to. 116 llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(E->getType()), 117 "reftmp"); 118 if (Val.isScalar()) 119 EmitStoreOfScalar(Val.getScalarVal(), Temp, false, E->getType()); 120 else 121 StoreComplexToAddr(Val.getComplexVal(), Temp, false); 122 Val = RValue::get(Temp); 123 } 124 125 return Val; 126 } 127 128 129 /// getAccessedFieldNo - Given an encoded value and a result number, return 130 /// the input field number being accessed. 131 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx, 132 const llvm::Constant *Elts) { 133 if (isa<llvm::ConstantAggregateZero>(Elts)) 134 return 0; 135 136 return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue(); 137 } 138 139 140 //===----------------------------------------------------------------------===// 141 // LValue Expression Emission 142 //===----------------------------------------------------------------------===// 143 144 RValue CodeGenFunction::GetUndefRValue(QualType Ty) { 145 if (Ty->isVoidType()) { 146 return RValue::get(0); 147 } else if (const ComplexType *CTy = Ty->getAsComplexType()) { 148 const llvm::Type *EltTy = ConvertType(CTy->getElementType()); 149 llvm::Value *U = llvm::UndefValue::get(EltTy); 150 return RValue::getComplex(std::make_pair(U, U)); 151 } else if (hasAggregateLLVMType(Ty)) { 152 const llvm::Type *LTy = llvm::PointerType::getUnqual(ConvertType(Ty)); 153 return RValue::getAggregate(llvm::UndefValue::get(LTy)); 154 } else { 155 return RValue::get(llvm::UndefValue::get(ConvertType(Ty))); 156 } 157 } 158 159 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E, 160 const char *Name) { 161 ErrorUnsupported(E, Name); 162 return GetUndefRValue(E->getType()); 163 } 164 165 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E, 166 const char *Name) { 167 ErrorUnsupported(E, Name); 168 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType())); 169 return LValue::MakeAddr(llvm::UndefValue::get(Ty), 170 E->getType().getCVRQualifiers(), 171 getContext().getObjCGCAttrKind(E->getType()), 172 E->getType().getAddressSpace()); 173 } 174 175 /// EmitLValue - Emit code to compute a designator that specifies the location 176 /// of the expression. 177 /// 178 /// This can return one of two things: a simple address or a bitfield 179 /// reference. In either case, the LLVM Value* in the LValue structure is 180 /// guaranteed to be an LLVM pointer type. 181 /// 182 /// If this returns a bitfield reference, nothing about the pointee type of 183 /// the LLVM value is known: For example, it may not be a pointer to an 184 /// integer. 185 /// 186 /// If this returns a normal address, and if the lvalue's C type is fixed 187 /// size, this method guarantees that the returned pointer type will point to 188 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a 189 /// variable length type, this is not possible. 190 /// 191 LValue CodeGenFunction::EmitLValue(const Expr *E) { 192 switch (E->getStmtClass()) { 193 default: return EmitUnsupportedLValue(E, "l-value expression"); 194 195 case Expr::BinaryOperatorClass: 196 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E)); 197 case Expr::CallExprClass: 198 case Expr::CXXOperatorCallExprClass: 199 return EmitCallExprLValue(cast<CallExpr>(E)); 200 case Expr::VAArgExprClass: 201 return EmitVAArgExprLValue(cast<VAArgExpr>(E)); 202 case Expr::DeclRefExprClass: 203 case Expr::QualifiedDeclRefExprClass: 204 return EmitDeclRefLValue(cast<DeclRefExpr>(E)); 205 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr()); 206 case Expr::PredefinedExprClass: 207 return EmitPredefinedLValue(cast<PredefinedExpr>(E)); 208 case Expr::StringLiteralClass: 209 return EmitStringLiteralLValue(cast<StringLiteral>(E)); 210 case Expr::ObjCEncodeExprClass: 211 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E)); 212 213 case Expr::BlockDeclRefExprClass: 214 return EmitBlockDeclRefLValue(cast<BlockDeclRefExpr>(E)); 215 216 case Expr::CXXConditionDeclExprClass: 217 return EmitCXXConditionDeclLValue(cast<CXXConditionDeclExpr>(E)); 218 case Expr::CXXTemporaryObjectExprClass: 219 case Expr::CXXConstructExprClass: 220 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E)); 221 case Expr::CXXBindTemporaryExprClass: 222 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E)); 223 224 case Expr::ObjCMessageExprClass: 225 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E)); 226 case Expr::ObjCIvarRefExprClass: 227 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E)); 228 case Expr::ObjCPropertyRefExprClass: 229 return EmitObjCPropertyRefLValue(cast<ObjCPropertyRefExpr>(E)); 230 case Expr::ObjCImplicitSetterGetterRefExprClass: 231 return EmitObjCKVCRefLValue(cast<ObjCImplicitSetterGetterRefExpr>(E)); 232 case Expr::ObjCSuperExprClass: 233 return EmitObjCSuperExprLValue(cast<ObjCSuperExpr>(E)); 234 235 case Expr::StmtExprClass: 236 return EmitStmtExprLValue(cast<StmtExpr>(E)); 237 case Expr::UnaryOperatorClass: 238 return EmitUnaryOpLValue(cast<UnaryOperator>(E)); 239 case Expr::ArraySubscriptExprClass: 240 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E)); 241 case Expr::ExtVectorElementExprClass: 242 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E)); 243 case Expr::MemberExprClass: 244 return EmitMemberExpr(cast<MemberExpr>(E)); 245 case Expr::CompoundLiteralExprClass: 246 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E)); 247 case Expr::ConditionalOperatorClass: 248 return EmitConditionalOperator(cast<ConditionalOperator>(E)); 249 case Expr::ChooseExprClass: 250 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext())); 251 case Expr::ImplicitCastExprClass: 252 case Expr::CStyleCastExprClass: 253 case Expr::CXXFunctionalCastExprClass: 254 case Expr::CXXStaticCastExprClass: 255 case Expr::CXXDynamicCastExprClass: 256 case Expr::CXXReinterpretCastExprClass: 257 case Expr::CXXConstCastExprClass: 258 return EmitCastLValue(cast<CastExpr>(E)); 259 } 260 } 261 262 llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile, 263 QualType Ty) { 264 llvm::Value *V = Builder.CreateLoad(Addr, Volatile, "tmp"); 265 266 // Bool can have different representation in memory than in registers. 267 if (Ty->isBooleanType()) 268 if (V->getType() != llvm::Type::getInt1Ty(VMContext)) 269 V = Builder.CreateTrunc(V, llvm::Type::getInt1Ty(VMContext), "tobool"); 270 271 return V; 272 } 273 274 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr, 275 bool Volatile, QualType Ty) { 276 277 if (Ty->isBooleanType()) { 278 // Bool can have different representation in memory than in registers. 279 const llvm::Type *SrcTy = Value->getType(); 280 const llvm::PointerType *DstPtr = cast<llvm::PointerType>(Addr->getType()); 281 if (DstPtr->getElementType() != SrcTy) { 282 const llvm::Type *MemTy = 283 llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace()); 284 Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp"); 285 } 286 } 287 Builder.CreateStore(Value, Addr, Volatile); 288 } 289 290 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, 291 /// this method emits the address of the lvalue, then loads the result as an 292 /// rvalue, returning the rvalue. 293 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) { 294 if (LV.isObjCWeak()) { 295 // load of a __weak object. 296 llvm::Value *AddrWeakObj = LV.getAddress(); 297 llvm::Value *read_weak = CGM.getObjCRuntime().EmitObjCWeakRead(*this, 298 AddrWeakObj); 299 return RValue::get(read_weak); 300 } 301 302 if (LV.isSimple()) { 303 llvm::Value *Ptr = LV.getAddress(); 304 const llvm::Type *EltTy = 305 cast<llvm::PointerType>(Ptr->getType())->getElementType(); 306 307 // Simple scalar l-value. 308 if (EltTy->isSingleValueType()) 309 return RValue::get(EmitLoadOfScalar(Ptr, LV.isVolatileQualified(), 310 ExprType)); 311 312 assert(ExprType->isFunctionType() && "Unknown scalar value"); 313 return RValue::get(Ptr); 314 } 315 316 if (LV.isVectorElt()) { 317 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), 318 LV.isVolatileQualified(), "tmp"); 319 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(), 320 "vecext")); 321 } 322 323 // If this is a reference to a subset of the elements of a vector, either 324 // shuffle the input or extract/insert them as appropriate. 325 if (LV.isExtVectorElt()) 326 return EmitLoadOfExtVectorElementLValue(LV, ExprType); 327 328 if (LV.isBitfield()) 329 return EmitLoadOfBitfieldLValue(LV, ExprType); 330 331 if (LV.isPropertyRef()) 332 return EmitLoadOfPropertyRefLValue(LV, ExprType); 333 334 assert(LV.isKVCRef() && "Unknown LValue type!"); 335 return EmitLoadOfKVCRefLValue(LV, ExprType); 336 } 337 338 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV, 339 QualType ExprType) { 340 unsigned StartBit = LV.getBitfieldStartBit(); 341 unsigned BitfieldSize = LV.getBitfieldSize(); 342 llvm::Value *Ptr = LV.getBitfieldAddr(); 343 344 const llvm::Type *EltTy = 345 cast<llvm::PointerType>(Ptr->getType())->getElementType(); 346 unsigned EltTySize = CGM.getTargetData().getTypeSizeInBits(EltTy); 347 348 // In some cases the bitfield may straddle two memory locations. 349 // Currently we load the entire bitfield, then do the magic to 350 // sign-extend it if necessary. This results in somewhat more code 351 // than necessary for the common case (one load), since two shifts 352 // accomplish both the masking and sign extension. 353 unsigned LowBits = std::min(BitfieldSize, EltTySize - StartBit); 354 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "tmp"); 355 356 // Shift to proper location. 357 if (StartBit) 358 Val = Builder.CreateLShr(Val, llvm::ConstantInt::get(EltTy, StartBit), 359 "bf.lo"); 360 361 // Mask off unused bits. 362 llvm::Constant *LowMask = llvm::ConstantInt::get(VMContext, 363 llvm::APInt::getLowBitsSet(EltTySize, LowBits)); 364 Val = Builder.CreateAnd(Val, LowMask, "bf.lo.cleared"); 365 366 // Fetch the high bits if necessary. 367 if (LowBits < BitfieldSize) { 368 unsigned HighBits = BitfieldSize - LowBits; 369 llvm::Value *HighPtr = Builder.CreateGEP(Ptr, llvm::ConstantInt::get( 370 llvm::Type::getInt32Ty(VMContext), 1), "bf.ptr.hi"); 371 llvm::Value *HighVal = Builder.CreateLoad(HighPtr, 372 LV.isVolatileQualified(), 373 "tmp"); 374 375 // Mask off unused bits. 376 llvm::Constant *HighMask = llvm::ConstantInt::get(VMContext, 377 llvm::APInt::getLowBitsSet(EltTySize, HighBits)); 378 HighVal = Builder.CreateAnd(HighVal, HighMask, "bf.lo.cleared"); 379 380 // Shift to proper location and or in to bitfield value. 381 HighVal = Builder.CreateShl(HighVal, 382 llvm::ConstantInt::get(EltTy, LowBits)); 383 Val = Builder.CreateOr(Val, HighVal, "bf.val"); 384 } 385 386 // Sign extend if necessary. 387 if (LV.isBitfieldSigned()) { 388 llvm::Value *ExtraBits = llvm::ConstantInt::get(EltTy, 389 EltTySize - BitfieldSize); 390 Val = Builder.CreateAShr(Builder.CreateShl(Val, ExtraBits), 391 ExtraBits, "bf.val.sext"); 392 } 393 394 // The bitfield type and the normal type differ when the storage sizes 395 // differ (currently just _Bool). 396 Val = Builder.CreateIntCast(Val, ConvertType(ExprType), false, "tmp"); 397 398 return RValue::get(Val); 399 } 400 401 RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV, 402 QualType ExprType) { 403 return EmitObjCPropertyGet(LV.getPropertyRefExpr()); 404 } 405 406 RValue CodeGenFunction::EmitLoadOfKVCRefLValue(LValue LV, 407 QualType ExprType) { 408 return EmitObjCPropertyGet(LV.getKVCRefExpr()); 409 } 410 411 // If this is a reference to a subset of the elements of a vector, create an 412 // appropriate shufflevector. 413 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV, 414 QualType ExprType) { 415 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(), 416 LV.isVolatileQualified(), "tmp"); 417 418 const llvm::Constant *Elts = LV.getExtVectorElts(); 419 420 // If the result of the expression is a non-vector type, we must be 421 // extracting a single element. Just codegen as an extractelement. 422 const VectorType *ExprVT = ExprType->getAsVectorType(); 423 if (!ExprVT) { 424 unsigned InIdx = getAccessedFieldNo(0, Elts); 425 llvm::Value *Elt = llvm::ConstantInt::get( 426 llvm::Type::getInt32Ty(VMContext), InIdx); 427 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp")); 428 } 429 430 // Always use shuffle vector to try to retain the original program structure 431 unsigned NumResultElts = ExprVT->getNumElements(); 432 433 llvm::SmallVector<llvm::Constant*, 4> Mask; 434 for (unsigned i = 0; i != NumResultElts; ++i) { 435 unsigned InIdx = getAccessedFieldNo(i, Elts); 436 Mask.push_back(llvm::ConstantInt::get( 437 llvm::Type::getInt32Ty(VMContext), InIdx)); 438 } 439 440 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size()); 441 Vec = Builder.CreateShuffleVector(Vec, 442 llvm::UndefValue::get(Vec->getType()), 443 MaskV, "tmp"); 444 return RValue::get(Vec); 445 } 446 447 448 449 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 450 /// lvalue, where both are guaranteed to the have the same type, and that type 451 /// is 'Ty'. 452 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, 453 QualType Ty) { 454 if (!Dst.isSimple()) { 455 if (Dst.isVectorElt()) { 456 // Read/modify/write the vector, inserting the new element. 457 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), 458 Dst.isVolatileQualified(), "tmp"); 459 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(), 460 Dst.getVectorIdx(), "vecins"); 461 Builder.CreateStore(Vec, Dst.getVectorAddr(),Dst.isVolatileQualified()); 462 return; 463 } 464 465 // If this is an update of extended vector elements, insert them as 466 // appropriate. 467 if (Dst.isExtVectorElt()) 468 return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty); 469 470 if (Dst.isBitfield()) 471 return EmitStoreThroughBitfieldLValue(Src, Dst, Ty); 472 473 if (Dst.isPropertyRef()) 474 return EmitStoreThroughPropertyRefLValue(Src, Dst, Ty); 475 476 if (Dst.isKVCRef()) 477 return EmitStoreThroughKVCRefLValue(Src, Dst, Ty); 478 479 assert(0 && "Unknown LValue type"); 480 } 481 482 if (Dst.isObjCWeak() && !Dst.isNonGC()) { 483 // load of a __weak object. 484 llvm::Value *LvalueDst = Dst.getAddress(); 485 llvm::Value *src = Src.getScalarVal(); 486 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst); 487 return; 488 } 489 490 if (Dst.isObjCStrong() && !Dst.isNonGC()) { 491 // load of a __strong object. 492 llvm::Value *LvalueDst = Dst.getAddress(); 493 llvm::Value *src = Src.getScalarVal(); 494 #if 0 495 // FIXME. We cannot positively determine if we have an 'ivar' assignment, 496 // object assignment or an unknown assignment. For now, generate call to 497 // objc_assign_strongCast assignment which is a safe, but consevative 498 // assumption. 499 if (Dst.isObjCIvar()) 500 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, LvalueDst); 501 else 502 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst); 503 #endif 504 if (Dst.isGlobalObjCRef()) 505 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst); 506 else 507 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst); 508 return; 509 } 510 511 assert(Src.isScalar() && "Can't emit an agg store with this method"); 512 EmitStoreOfScalar(Src.getScalarVal(), Dst.getAddress(), 513 Dst.isVolatileQualified(), Ty); 514 } 515 516 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 517 QualType Ty, 518 llvm::Value **Result) { 519 unsigned StartBit = Dst.getBitfieldStartBit(); 520 unsigned BitfieldSize = Dst.getBitfieldSize(); 521 llvm::Value *Ptr = Dst.getBitfieldAddr(); 522 523 const llvm::Type *EltTy = 524 cast<llvm::PointerType>(Ptr->getType())->getElementType(); 525 unsigned EltTySize = CGM.getTargetData().getTypeSizeInBits(EltTy); 526 527 // Get the new value, cast to the appropriate type and masked to 528 // exactly the size of the bit-field. 529 llvm::Value *SrcVal = Src.getScalarVal(); 530 llvm::Value *NewVal = Builder.CreateIntCast(SrcVal, EltTy, false, "tmp"); 531 llvm::Constant *Mask = llvm::ConstantInt::get(VMContext, 532 llvm::APInt::getLowBitsSet(EltTySize, BitfieldSize)); 533 NewVal = Builder.CreateAnd(NewVal, Mask, "bf.value"); 534 535 // Return the new value of the bit-field, if requested. 536 if (Result) { 537 // Cast back to the proper type for result. 538 const llvm::Type *SrcTy = SrcVal->getType(); 539 llvm::Value *SrcTrunc = Builder.CreateIntCast(NewVal, SrcTy, false, 540 "bf.reload.val"); 541 542 // Sign extend if necessary. 543 if (Dst.isBitfieldSigned()) { 544 unsigned SrcTySize = CGM.getTargetData().getTypeSizeInBits(SrcTy); 545 llvm::Value *ExtraBits = llvm::ConstantInt::get(SrcTy, 546 SrcTySize - BitfieldSize); 547 SrcTrunc = Builder.CreateAShr(Builder.CreateShl(SrcTrunc, ExtraBits), 548 ExtraBits, "bf.reload.sext"); 549 } 550 551 *Result = SrcTrunc; 552 } 553 554 // In some cases the bitfield may straddle two memory locations. 555 // Emit the low part first and check to see if the high needs to be 556 // done. 557 unsigned LowBits = std::min(BitfieldSize, EltTySize - StartBit); 558 llvm::Value *LowVal = Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), 559 "bf.prev.low"); 560 561 // Compute the mask for zero-ing the low part of this bitfield. 562 llvm::Constant *InvMask = 563 llvm::ConstantInt::get(VMContext, 564 ~llvm::APInt::getBitsSet(EltTySize, StartBit, StartBit + LowBits)); 565 566 // Compute the new low part as 567 // LowVal = (LowVal & InvMask) | (NewVal << StartBit), 568 // with the shift of NewVal implicitly stripping the high bits. 569 llvm::Value *NewLowVal = 570 Builder.CreateShl(NewVal, llvm::ConstantInt::get(EltTy, StartBit), 571 "bf.value.lo"); 572 LowVal = Builder.CreateAnd(LowVal, InvMask, "bf.prev.lo.cleared"); 573 LowVal = Builder.CreateOr(LowVal, NewLowVal, "bf.new.lo"); 574 575 // Write back. 576 Builder.CreateStore(LowVal, Ptr, Dst.isVolatileQualified()); 577 578 // If the low part doesn't cover the bitfield emit a high part. 579 if (LowBits < BitfieldSize) { 580 unsigned HighBits = BitfieldSize - LowBits; 581 llvm::Value *HighPtr = Builder.CreateGEP(Ptr, llvm::ConstantInt::get( 582 llvm::Type::getInt32Ty(VMContext), 1), "bf.ptr.hi"); 583 llvm::Value *HighVal = Builder.CreateLoad(HighPtr, 584 Dst.isVolatileQualified(), 585 "bf.prev.hi"); 586 587 // Compute the mask for zero-ing the high part of this bitfield. 588 llvm::Constant *InvMask = 589 llvm::ConstantInt::get(VMContext, ~llvm::APInt::getLowBitsSet(EltTySize, 590 HighBits)); 591 592 // Compute the new high part as 593 // HighVal = (HighVal & InvMask) | (NewVal lshr LowBits), 594 // where the high bits of NewVal have already been cleared and the 595 // shift stripping the low bits. 596 llvm::Value *NewHighVal = 597 Builder.CreateLShr(NewVal, llvm::ConstantInt::get(EltTy, LowBits), 598 "bf.value.high"); 599 HighVal = Builder.CreateAnd(HighVal, InvMask, "bf.prev.hi.cleared"); 600 HighVal = Builder.CreateOr(HighVal, NewHighVal, "bf.new.hi"); 601 602 // Write back. 603 Builder.CreateStore(HighVal, HighPtr, Dst.isVolatileQualified()); 604 } 605 } 606 607 void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src, 608 LValue Dst, 609 QualType Ty) { 610 EmitObjCPropertySet(Dst.getPropertyRefExpr(), Src); 611 } 612 613 void CodeGenFunction::EmitStoreThroughKVCRefLValue(RValue Src, 614 LValue Dst, 615 QualType Ty) { 616 EmitObjCPropertySet(Dst.getKVCRefExpr(), Src); 617 } 618 619 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src, 620 LValue Dst, 621 QualType Ty) { 622 // This access turns into a read/modify/write of the vector. Load the input 623 // value now. 624 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(), 625 Dst.isVolatileQualified(), "tmp"); 626 const llvm::Constant *Elts = Dst.getExtVectorElts(); 627 628 llvm::Value *SrcVal = Src.getScalarVal(); 629 630 if (const VectorType *VTy = Ty->getAsVectorType()) { 631 unsigned NumSrcElts = VTy->getNumElements(); 632 unsigned NumDstElts = 633 cast<llvm::VectorType>(Vec->getType())->getNumElements(); 634 if (NumDstElts == NumSrcElts) { 635 // Use shuffle vector is the src and destination are the same number 636 // of elements and restore the vector mask since it is on the side 637 // it will be stored. 638 llvm::SmallVector<llvm::Constant*, 4> Mask(NumDstElts); 639 for (unsigned i = 0; i != NumSrcElts; ++i) { 640 unsigned InIdx = getAccessedFieldNo(i, Elts); 641 Mask[InIdx] = llvm::ConstantInt::get( 642 llvm::Type::getInt32Ty(VMContext), i); 643 } 644 645 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size()); 646 Vec = Builder.CreateShuffleVector(SrcVal, 647 llvm::UndefValue::get(Vec->getType()), 648 MaskV, "tmp"); 649 } else if (NumDstElts > NumSrcElts) { 650 // Extended the source vector to the same length and then shuffle it 651 // into the destination. 652 // FIXME: since we're shuffling with undef, can we just use the indices 653 // into that? This could be simpler. 654 llvm::SmallVector<llvm::Constant*, 4> ExtMask; 655 unsigned i; 656 for (i = 0; i != NumSrcElts; ++i) 657 ExtMask.push_back(llvm::ConstantInt::get( 658 llvm::Type::getInt32Ty(VMContext), i)); 659 for (; i != NumDstElts; ++i) 660 ExtMask.push_back(llvm::UndefValue::get( 661 llvm::Type::getInt32Ty(VMContext))); 662 llvm::Value *ExtMaskV = llvm::ConstantVector::get(&ExtMask[0], 663 ExtMask.size()); 664 llvm::Value *ExtSrcVal = 665 Builder.CreateShuffleVector(SrcVal, 666 llvm::UndefValue::get(SrcVal->getType()), 667 ExtMaskV, "tmp"); 668 // build identity 669 llvm::SmallVector<llvm::Constant*, 4> Mask; 670 for (unsigned i = 0; i != NumDstElts; ++i) { 671 Mask.push_back(llvm::ConstantInt::get( 672 llvm::Type::getInt32Ty(VMContext), i)); 673 } 674 // modify when what gets shuffled in 675 for (unsigned i = 0; i != NumSrcElts; ++i) { 676 unsigned Idx = getAccessedFieldNo(i, Elts); 677 Mask[Idx] = llvm::ConstantInt::get( 678 llvm::Type::getInt32Ty(VMContext), i+NumDstElts); 679 } 680 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size()); 681 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV, "tmp"); 682 } else { 683 // We should never shorten the vector 684 assert(0 && "unexpected shorten vector length"); 685 } 686 } else { 687 // If the Src is a scalar (not a vector) it must be updating one element. 688 unsigned InIdx = getAccessedFieldNo(0, Elts); 689 llvm::Value *Elt = llvm::ConstantInt::get( 690 llvm::Type::getInt32Ty(VMContext), InIdx); 691 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp"); 692 } 693 694 Builder.CreateStore(Vec, Dst.getExtVectorAddr(), Dst.isVolatileQualified()); 695 } 696 697 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) { 698 const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()); 699 700 if (VD && (VD->isBlockVarDecl() || isa<ParmVarDecl>(VD) || 701 isa<ImplicitParamDecl>(VD))) { 702 LValue LV; 703 bool NonGCable = VD->hasLocalStorage() && 704 !VD->hasAttr<BlocksAttr>(); 705 if (VD->hasExternalStorage()) { 706 llvm::Value *V = CGM.GetAddrOfGlobalVar(VD); 707 if (VD->getType()->isReferenceType()) 708 V = Builder.CreateLoad(V, "tmp"); 709 LV = LValue::MakeAddr(V, E->getType().getCVRQualifiers(), 710 getContext().getObjCGCAttrKind(E->getType()), 711 E->getType().getAddressSpace()); 712 } else { 713 llvm::Value *V = LocalDeclMap[VD]; 714 assert(V && "DeclRefExpr not entered in LocalDeclMap?"); 715 // local variables do not get their gc attribute set. 716 QualType::GCAttrTypes attr = QualType::GCNone; 717 // local static? 718 if (!NonGCable) 719 attr = getContext().getObjCGCAttrKind(E->getType()); 720 if (VD->hasAttr<BlocksAttr>()) { 721 bool needsCopyDispose = BlockRequiresCopying(VD->getType()); 722 const llvm::Type *PtrStructTy = V->getType(); 723 const llvm::Type *Ty = PtrStructTy; 724 Ty = llvm::PointerType::get(Ty, 0); 725 V = Builder.CreateStructGEP(V, 1, "forwarding"); 726 V = Builder.CreateBitCast(V, Ty); 727 V = Builder.CreateLoad(V, false); 728 V = Builder.CreateBitCast(V, PtrStructTy); 729 V = Builder.CreateStructGEP(V, needsCopyDispose*2 + 4, "x"); 730 } 731 if (VD->getType()->isReferenceType()) 732 V = Builder.CreateLoad(V, "tmp"); 733 LV = LValue::MakeAddr(V, E->getType().getCVRQualifiers(), attr, 734 E->getType().getAddressSpace()); 735 } 736 LValue::SetObjCNonGC(LV, NonGCable); 737 return LV; 738 } else if (VD && VD->isFileVarDecl()) { 739 llvm::Value *V = CGM.GetAddrOfGlobalVar(VD); 740 if (VD->getType()->isReferenceType()) 741 V = Builder.CreateLoad(V, "tmp"); 742 LValue LV = LValue::MakeAddr(V, E->getType().getCVRQualifiers(), 743 getContext().getObjCGCAttrKind(E->getType()), 744 E->getType().getAddressSpace()); 745 if (LV.isObjCStrong()) 746 LV.SetGlobalObjCRef(LV, true); 747 return LV; 748 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) { 749 llvm::Value* V = CGM.GetAddrOfFunction(GlobalDecl(FD)); 750 if (!FD->hasPrototype()) { 751 if (const FunctionProtoType *Proto = 752 FD->getType()->getAsFunctionProtoType()) { 753 // Ugly case: for a K&R-style definition, the type of the definition 754 // isn't the same as the type of a use. Correct for this with a 755 // bitcast. 756 QualType NoProtoType = 757 getContext().getFunctionNoProtoType(Proto->getResultType()); 758 NoProtoType = getContext().getPointerType(NoProtoType); 759 V = Builder.CreateBitCast(V, ConvertType(NoProtoType), "tmp"); 760 } 761 } 762 return LValue::MakeAddr(V, E->getType().getCVRQualifiers(), 763 getContext().getObjCGCAttrKind(E->getType()), 764 E->getType().getAddressSpace()); 765 } else if (const ImplicitParamDecl *IPD = 766 dyn_cast<ImplicitParamDecl>(E->getDecl())) { 767 llvm::Value *V = LocalDeclMap[IPD]; 768 assert(V && "BlockVarDecl not entered in LocalDeclMap?"); 769 return LValue::MakeAddr(V, E->getType().getCVRQualifiers(), 770 getContext().getObjCGCAttrKind(E->getType()), 771 E->getType().getAddressSpace()); 772 } 773 assert(0 && "Unimp declref"); 774 //an invalid LValue, but the assert will 775 //ensure that this point is never reached. 776 return LValue(); 777 } 778 779 LValue CodeGenFunction::EmitBlockDeclRefLValue(const BlockDeclRefExpr *E) { 780 return LValue::MakeAddr(GetAddrOfBlockDecl(E), 781 E->getType().getCVRQualifiers(), 782 getContext().getObjCGCAttrKind(E->getType()), 783 E->getType().getAddressSpace()); 784 } 785 786 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) { 787 // __extension__ doesn't affect lvalue-ness. 788 if (E->getOpcode() == UnaryOperator::Extension) 789 return EmitLValue(E->getSubExpr()); 790 791 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType()); 792 switch (E->getOpcode()) { 793 default: assert(0 && "Unknown unary operator lvalue!"); 794 case UnaryOperator::Deref: 795 { 796 QualType T = E->getSubExpr()->getType()->getPointeeType(); 797 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type"); 798 799 LValue LV = LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()), 800 T.getCVRQualifiers(), 801 getContext().getObjCGCAttrKind(T), 802 ExprTy.getAddressSpace()); 803 // We should not generate __weak write barrier on indirect reference 804 // of a pointer to object; as in void foo (__weak id *param); *param = 0; 805 // But, we continue to generate __strong write barrier on indirect write 806 // into a pointer to object. 807 if (getContext().getLangOptions().ObjC1 && 808 getContext().getLangOptions().getGCMode() != LangOptions::NonGC && 809 LV.isObjCWeak()) 810 LValue::SetObjCNonGC(LV, !E->isOBJCGCCandidate(getContext())); 811 return LV; 812 } 813 case UnaryOperator::Real: 814 case UnaryOperator::Imag: 815 LValue LV = EmitLValue(E->getSubExpr()); 816 unsigned Idx = E->getOpcode() == UnaryOperator::Imag; 817 return LValue::MakeAddr(Builder.CreateStructGEP(LV.getAddress(), 818 Idx, "idx"), 819 ExprTy.getCVRQualifiers(), 820 QualType::GCNone, 821 ExprTy.getAddressSpace()); 822 } 823 } 824 825 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) { 826 return LValue::MakeAddr(CGM.GetAddrOfConstantStringFromLiteral(E), 0); 827 } 828 829 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) { 830 return LValue::MakeAddr(CGM.GetAddrOfConstantStringFromObjCEncode(E), 0); 831 } 832 833 834 LValue CodeGenFunction::EmitPredefinedFunctionName(unsigned Type) { 835 std::string GlobalVarName; 836 837 switch (Type) { 838 default: 839 assert(0 && "Invalid type"); 840 case PredefinedExpr::Func: 841 GlobalVarName = "__func__."; 842 break; 843 case PredefinedExpr::Function: 844 GlobalVarName = "__FUNCTION__."; 845 break; 846 case PredefinedExpr::PrettyFunction: 847 // FIXME:: Demangle C++ method names 848 GlobalVarName = "__PRETTY_FUNCTION__."; 849 break; 850 } 851 852 // FIXME: This isn't right at all. The logic for computing this should go 853 // into a method on PredefinedExpr. This would allow sema and codegen to be 854 // consistent for things like sizeof(__func__) etc. 855 std::string FunctionName; 856 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) { 857 FunctionName = CGM.getMangledName(FD); 858 } else { 859 // Just get the mangled name; skipping the asm prefix if it 860 // exists. 861 FunctionName = CurFn->getName(); 862 if (FunctionName[0] == '\01') 863 FunctionName = FunctionName.substr(1, std::string::npos); 864 } 865 866 GlobalVarName += FunctionName; 867 llvm::Constant *C = 868 CGM.GetAddrOfConstantCString(FunctionName, GlobalVarName.c_str()); 869 return LValue::MakeAddr(C, 0); 870 } 871 872 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) { 873 switch (E->getIdentType()) { 874 default: 875 return EmitUnsupportedLValue(E, "predefined expression"); 876 case PredefinedExpr::Func: 877 case PredefinedExpr::Function: 878 case PredefinedExpr::PrettyFunction: 879 return EmitPredefinedFunctionName(E->getIdentType()); 880 } 881 } 882 883 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) { 884 // The index must always be an integer, which is not an aggregate. Emit it. 885 llvm::Value *Idx = EmitScalarExpr(E->getIdx()); 886 QualType IdxTy = E->getIdx()->getType(); 887 bool IdxSigned = IdxTy->isSignedIntegerType(); 888 889 // If the base is a vector type, then we are forming a vector element lvalue 890 // with this subscript. 891 if (E->getBase()->getType()->isVectorType()) { 892 // Emit the vector as an lvalue to get its address. 893 LValue LHS = EmitLValue(E->getBase()); 894 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!"); 895 Idx = Builder.CreateIntCast(Idx, 896 llvm::Type::getInt32Ty(VMContext), IdxSigned, "vidx"); 897 return LValue::MakeVectorElt(LHS.getAddress(), Idx, 898 E->getBase()->getType().getCVRQualifiers()); 899 } 900 901 // The base must be a pointer, which is not an aggregate. Emit it. 902 llvm::Value *Base = EmitScalarExpr(E->getBase()); 903 904 // Extend or truncate the index type to 32 or 64-bits. 905 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth(); 906 if (IdxBitwidth != LLVMPointerWidth) 907 Idx = Builder.CreateIntCast(Idx, 908 llvm::IntegerType::get(VMContext, LLVMPointerWidth), 909 IdxSigned, "idxprom"); 910 911 // We know that the pointer points to a type of the correct size, 912 // unless the size is a VLA or Objective-C interface. 913 llvm::Value *Address = 0; 914 if (const VariableArrayType *VAT = 915 getContext().getAsVariableArrayType(E->getType())) { 916 llvm::Value *VLASize = GetVLASize(VAT); 917 918 Idx = Builder.CreateMul(Idx, VLASize); 919 920 QualType BaseType = getContext().getBaseElementType(VAT); 921 922 uint64_t BaseTypeSize = getContext().getTypeSize(BaseType) / 8; 923 Idx = Builder.CreateUDiv(Idx, 924 llvm::ConstantInt::get(Idx->getType(), 925 BaseTypeSize)); 926 Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx"); 927 } else if (const ObjCInterfaceType *OIT = 928 dyn_cast<ObjCInterfaceType>(E->getType())) { 929 llvm::Value *InterfaceSize = 930 llvm::ConstantInt::get(Idx->getType(), 931 getContext().getTypeSize(OIT) / 8); 932 933 Idx = Builder.CreateMul(Idx, InterfaceSize); 934 935 llvm::Type *i8PTy = 936 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext)); 937 Address = Builder.CreateGEP(Builder.CreateBitCast(Base, i8PTy), 938 Idx, "arrayidx"); 939 Address = Builder.CreateBitCast(Address, Base->getType()); 940 } else { 941 Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx"); 942 } 943 944 QualType T = E->getBase()->getType()->getPointeeType(); 945 assert(!T.isNull() && 946 "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type"); 947 948 LValue LV = LValue::MakeAddr(Address, 949 T.getCVRQualifiers(), 950 getContext().getObjCGCAttrKind(T), 951 E->getBase()->getType().getAddressSpace()); 952 if (getContext().getLangOptions().ObjC1 && 953 getContext().getLangOptions().getGCMode() != LangOptions::NonGC) 954 LValue::SetObjCNonGC(LV, !E->isOBJCGCCandidate(getContext())); 955 return LV; 956 } 957 958 static 959 llvm::Constant *GenerateConstantVector(llvm::LLVMContext &VMContext, 960 llvm::SmallVector<unsigned, 4> &Elts) { 961 llvm::SmallVector<llvm::Constant *, 4> CElts; 962 963 for (unsigned i = 0, e = Elts.size(); i != e; ++i) 964 CElts.push_back(llvm::ConstantInt::get( 965 llvm::Type::getInt32Ty(VMContext), Elts[i])); 966 967 return llvm::ConstantVector::get(&CElts[0], CElts.size()); 968 } 969 970 LValue CodeGenFunction:: 971 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) { 972 // Emit the base vector as an l-value. 973 LValue Base; 974 975 // ExtVectorElementExpr's base can either be a vector or pointer to vector. 976 if (!E->isArrow()) { 977 assert(E->getBase()->getType()->isVectorType()); 978 Base = EmitLValue(E->getBase()); 979 } else { 980 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>(); 981 llvm::Value *Ptr = EmitScalarExpr(E->getBase()); 982 Base = LValue::MakeAddr(Ptr, PT->getPointeeType().getCVRQualifiers(), 983 QualType::GCNone, 984 PT->getPointeeType().getAddressSpace()); 985 } 986 987 // Encode the element access list into a vector of unsigned indices. 988 llvm::SmallVector<unsigned, 4> Indices; 989 E->getEncodedElementAccess(Indices); 990 991 if (Base.isSimple()) { 992 llvm::Constant *CV = GenerateConstantVector(VMContext, Indices); 993 return LValue::MakeExtVectorElt(Base.getAddress(), CV, 994 Base.getQualifiers()); 995 } 996 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!"); 997 998 llvm::Constant *BaseElts = Base.getExtVectorElts(); 999 llvm::SmallVector<llvm::Constant *, 4> CElts; 1000 1001 for (unsigned i = 0, e = Indices.size(); i != e; ++i) { 1002 if (isa<llvm::ConstantAggregateZero>(BaseElts)) 1003 CElts.push_back(llvm::ConstantInt::get( 1004 llvm::Type::getInt32Ty(VMContext), 0)); 1005 else 1006 CElts.push_back(BaseElts->getOperand(Indices[i])); 1007 } 1008 llvm::Constant *CV = llvm::ConstantVector::get(&CElts[0], CElts.size()); 1009 return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, 1010 Base.getQualifiers()); 1011 } 1012 1013 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) { 1014 bool isUnion = false; 1015 bool isIvar = false; 1016 bool isNonGC = false; 1017 Expr *BaseExpr = E->getBase(); 1018 llvm::Value *BaseValue = NULL; 1019 unsigned CVRQualifiers=0; 1020 1021 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 1022 if (E->isArrow()) { 1023 BaseValue = EmitScalarExpr(BaseExpr); 1024 const PointerType *PTy = 1025 BaseExpr->getType()->getAs<PointerType>(); 1026 if (PTy->getPointeeType()->isUnionType()) 1027 isUnion = true; 1028 CVRQualifiers = PTy->getPointeeType().getCVRQualifiers(); 1029 } else if (isa<ObjCPropertyRefExpr>(BaseExpr) || 1030 isa<ObjCImplicitSetterGetterRefExpr>(BaseExpr)) { 1031 RValue RV = EmitObjCPropertyGet(BaseExpr); 1032 BaseValue = RV.getAggregateAddr(); 1033 if (BaseExpr->getType()->isUnionType()) 1034 isUnion = true; 1035 CVRQualifiers = BaseExpr->getType().getCVRQualifiers(); 1036 } else { 1037 LValue BaseLV = EmitLValue(BaseExpr); 1038 if (BaseLV.isObjCIvar()) 1039 isIvar = true; 1040 if (BaseLV.isNonGC()) 1041 isNonGC = true; 1042 // FIXME: this isn't right for bitfields. 1043 BaseValue = BaseLV.getAddress(); 1044 QualType BaseTy = BaseExpr->getType(); 1045 if (BaseTy->isUnionType()) 1046 isUnion = true; 1047 CVRQualifiers = BaseTy.getCVRQualifiers(); 1048 } 1049 1050 FieldDecl *Field = dyn_cast<FieldDecl>(E->getMemberDecl()); 1051 // FIXME: Handle non-field member expressions 1052 assert(Field && "No code generation for non-field member references"); 1053 LValue MemExpLV = EmitLValueForField(BaseValue, Field, isUnion, 1054 CVRQualifiers); 1055 LValue::SetObjCIvar(MemExpLV, isIvar); 1056 LValue::SetObjCNonGC(MemExpLV, isNonGC); 1057 return MemExpLV; 1058 } 1059 1060 LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value* BaseValue, 1061 FieldDecl* Field, 1062 unsigned CVRQualifiers) { 1063 CodeGenTypes::BitFieldInfo Info = CGM.getTypes().getBitFieldInfo(Field); 1064 1065 // FIXME: CodeGenTypes should expose a method to get the appropriate type for 1066 // FieldTy (the appropriate type is ABI-dependent). 1067 const llvm::Type *FieldTy = 1068 CGM.getTypes().ConvertTypeForMem(Field->getType()); 1069 const llvm::PointerType *BaseTy = 1070 cast<llvm::PointerType>(BaseValue->getType()); 1071 unsigned AS = BaseTy->getAddressSpace(); 1072 BaseValue = Builder.CreateBitCast(BaseValue, 1073 llvm::PointerType::get(FieldTy, AS), 1074 "tmp"); 1075 1076 llvm::Value *Idx = 1077 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Info.FieldNo); 1078 llvm::Value *V = Builder.CreateGEP(BaseValue, Idx, "tmp"); 1079 1080 return LValue::MakeBitfield(V, Info.Start, Info.Size, 1081 Field->getType()->isSignedIntegerType(), 1082 Field->getType().getCVRQualifiers()|CVRQualifiers); 1083 } 1084 1085 LValue CodeGenFunction::EmitLValueForField(llvm::Value* BaseValue, 1086 FieldDecl* Field, 1087 bool isUnion, 1088 unsigned CVRQualifiers) 1089 { 1090 if (Field->isBitField()) 1091 return EmitLValueForBitfield(BaseValue, Field, CVRQualifiers); 1092 1093 unsigned idx = CGM.getTypes().getLLVMFieldNo(Field); 1094 llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp"); 1095 1096 // Match union field type. 1097 if (isUnion) { 1098 const llvm::Type *FieldTy = 1099 CGM.getTypes().ConvertTypeForMem(Field->getType()); 1100 const llvm::PointerType * BaseTy = 1101 cast<llvm::PointerType>(BaseValue->getType()); 1102 unsigned AS = BaseTy->getAddressSpace(); 1103 V = Builder.CreateBitCast(V, 1104 llvm::PointerType::get(FieldTy, AS), 1105 "tmp"); 1106 } 1107 if (Field->getType()->isReferenceType()) 1108 V = Builder.CreateLoad(V, "tmp"); 1109 1110 QualType::GCAttrTypes attr = QualType::GCNone; 1111 if (CGM.getLangOptions().ObjC1 && 1112 CGM.getLangOptions().getGCMode() != LangOptions::NonGC) { 1113 QualType Ty = Field->getType(); 1114 attr = Ty.getObjCGCAttr(); 1115 if (attr != QualType::GCNone) { 1116 // __weak attribute on a field is ignored. 1117 if (attr == QualType::Weak) 1118 attr = QualType::GCNone; 1119 } else if (Ty->isObjCObjectPointerType()) 1120 attr = QualType::Strong; 1121 } 1122 LValue LV = 1123 LValue::MakeAddr(V, 1124 Field->getType().getCVRQualifiers()|CVRQualifiers, 1125 attr, 1126 Field->getType().getAddressSpace()); 1127 return LV; 1128 } 1129 1130 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr* E){ 1131 const llvm::Type *LTy = ConvertType(E->getType()); 1132 llvm::Value *DeclPtr = CreateTempAlloca(LTy, ".compoundliteral"); 1133 1134 const Expr* InitExpr = E->getInitializer(); 1135 LValue Result = LValue::MakeAddr(DeclPtr, E->getType().getCVRQualifiers(), 1136 QualType::GCNone, 1137 E->getType().getAddressSpace()); 1138 1139 if (E->getType()->isComplexType()) { 1140 EmitComplexExprIntoAddr(InitExpr, DeclPtr, false); 1141 } else if (hasAggregateLLVMType(E->getType())) { 1142 EmitAnyExpr(InitExpr, DeclPtr, false); 1143 } else { 1144 EmitStoreThroughLValue(EmitAnyExpr(InitExpr), Result, E->getType()); 1145 } 1146 1147 return Result; 1148 } 1149 1150 LValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator* E) { 1151 if (E->isLvalue(getContext()) == Expr::LV_Valid) 1152 return EmitUnsupportedLValue(E, "conditional operator"); 1153 1154 // ?: here should be an aggregate. 1155 assert((hasAggregateLLVMType(E->getType()) && 1156 !E->getType()->isAnyComplexType()) && 1157 "Unexpected conditional operator!"); 1158 1159 llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType())); 1160 EmitAggExpr(E, Temp, false); 1161 1162 return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(), 1163 getContext().getObjCGCAttrKind(E->getType()), 1164 E->getType().getAddressSpace()); 1165 1166 } 1167 1168 /// EmitCastLValue - Casts are never lvalues. If a cast is needed by the code 1169 /// generator in an lvalue context, then it must mean that we need the address 1170 /// of an aggregate in order to access one of its fields. This can happen for 1171 /// all the reasons that casts are permitted with aggregate result, including 1172 /// noop aggregate casts, and cast from scalar to union. 1173 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) { 1174 if (E->getCastKind() == CastExpr::CK_UserDefinedConversion) { 1175 if (const CXXFunctionalCastExpr *CXXFExpr = 1176 dyn_cast<CXXFunctionalCastExpr>(E)) 1177 return LValue::MakeAddr( 1178 EmitCXXFunctionalCastExpr(CXXFExpr).getScalarVal(), 0); 1179 assert(isa<CStyleCastExpr>(E) && 1180 "EmitCastLValue - Expected CStyleCastExpr"); 1181 return EmitLValue(E->getSubExpr()); 1182 } 1183 1184 // If this is an aggregate-to-aggregate cast, just use the input's address as 1185 // the lvalue. 1186 if (E->getCastKind() == CastExpr::CK_NoOp) 1187 return EmitLValue(E->getSubExpr()); 1188 1189 // If this is an lvalue cast, treat it as a no-op. 1190 // FIXME: We shouldn't need to check for this explicitly! 1191 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 1192 if (ICE->isLvalueCast()) 1193 return EmitLValue(E->getSubExpr()); 1194 1195 // Otherwise, we must have a cast from scalar to union. 1196 assert(E->getCastKind() == CastExpr::CK_ToUnion && 1197 "Expected scalar-to-union cast"); 1198 1199 // Casts are only lvalues when the source and destination types are the same. 1200 llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType())); 1201 EmitAnyExpr(E->getSubExpr(), Temp, false); 1202 1203 return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(), 1204 getContext().getObjCGCAttrKind(E->getType()), 1205 E->getType().getAddressSpace()); 1206 } 1207 1208 //===--------------------------------------------------------------------===// 1209 // Expression Emission 1210 //===--------------------------------------------------------------------===// 1211 1212 1213 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) { 1214 // Builtins never have block type. 1215 if (E->getCallee()->getType()->isBlockPointerType()) 1216 return EmitBlockCallExpr(E); 1217 1218 if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E)) 1219 return EmitCXXMemberCallExpr(CE); 1220 1221 const Decl *TargetDecl = 0; 1222 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E->getCallee())) { 1223 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) { 1224 TargetDecl = DRE->getDecl(); 1225 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(TargetDecl)) 1226 if (unsigned builtinID = FD->getBuiltinID(getContext())) 1227 return EmitBuiltinExpr(FD, builtinID, E); 1228 } 1229 } 1230 1231 if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E)) 1232 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl)) 1233 return EmitCXXOperatorMemberCallExpr(CE, MD); 1234 1235 llvm::Value *Callee = EmitScalarExpr(E->getCallee()); 1236 return EmitCall(Callee, E->getCallee()->getType(), 1237 E->arg_begin(), E->arg_end(), TargetDecl); 1238 } 1239 1240 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) { 1241 // Comma expressions just emit their LHS then their RHS as an l-value. 1242 if (E->getOpcode() == BinaryOperator::Comma) { 1243 EmitAnyExpr(E->getLHS()); 1244 return EmitLValue(E->getRHS()); 1245 } 1246 1247 // Can only get l-value for binary operator expressions which are a 1248 // simple assignment of aggregate type. 1249 if (E->getOpcode() != BinaryOperator::Assign) 1250 return EmitUnsupportedLValue(E, "binary l-value expression"); 1251 1252 llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType())); 1253 EmitAggExpr(E, Temp, false); 1254 // FIXME: Are these qualifiers correct? 1255 return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(), 1256 getContext().getObjCGCAttrKind(E->getType()), 1257 E->getType().getAddressSpace()); 1258 } 1259 1260 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) { 1261 RValue RV = EmitCallExpr(E); 1262 1263 if (RV.isScalar()) { 1264 assert(E->getCallReturnType()->isReferenceType() && 1265 "Can't have a scalar return unless the return type is a " 1266 "reference type!"); 1267 1268 return LValue::MakeAddr(RV.getScalarVal(), E->getType().getCVRQualifiers(), 1269 getContext().getObjCGCAttrKind(E->getType()), 1270 E->getType().getAddressSpace()); 1271 } 1272 1273 return LValue::MakeAddr(RV.getAggregateAddr(), 1274 E->getType().getCVRQualifiers(), 1275 getContext().getObjCGCAttrKind(E->getType()), 1276 E->getType().getAddressSpace()); 1277 } 1278 1279 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) { 1280 // FIXME: This shouldn't require another copy. 1281 llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType())); 1282 EmitAggExpr(E, Temp, false); 1283 return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(), 1284 QualType::GCNone, E->getType().getAddressSpace()); 1285 } 1286 1287 LValue 1288 CodeGenFunction::EmitCXXConditionDeclLValue(const CXXConditionDeclExpr *E) { 1289 EmitLocalBlockVarDecl(*E->getVarDecl()); 1290 return EmitDeclRefLValue(E); 1291 } 1292 1293 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) { 1294 llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(E->getType()), "tmp"); 1295 EmitCXXConstructExpr(Temp, E); 1296 return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(), 1297 QualType::GCNone, E->getType().getAddressSpace()); 1298 } 1299 1300 LValue 1301 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) { 1302 LValue LV = EmitLValue(E->getSubExpr()); 1303 1304 PushCXXTemporary(E->getTemporary(), LV.getAddress()); 1305 1306 return LV; 1307 } 1308 1309 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) { 1310 // Can only get l-value for message expression returning aggregate type 1311 RValue RV = EmitObjCMessageExpr(E); 1312 // FIXME: can this be volatile? 1313 return LValue::MakeAddr(RV.getAggregateAddr(), 1314 E->getType().getCVRQualifiers(), 1315 getContext().getObjCGCAttrKind(E->getType()), 1316 E->getType().getAddressSpace()); 1317 } 1318 1319 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface, 1320 const ObjCIvarDecl *Ivar) { 1321 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar); 1322 } 1323 1324 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy, 1325 llvm::Value *BaseValue, 1326 const ObjCIvarDecl *Ivar, 1327 unsigned CVRQualifiers) { 1328 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue, 1329 Ivar, CVRQualifiers); 1330 } 1331 1332 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) { 1333 // FIXME: A lot of the code below could be shared with EmitMemberExpr. 1334 llvm::Value *BaseValue = 0; 1335 const Expr *BaseExpr = E->getBase(); 1336 unsigned CVRQualifiers = 0; 1337 QualType ObjectTy; 1338 if (E->isArrow()) { 1339 BaseValue = EmitScalarExpr(BaseExpr); 1340 ObjectTy = BaseExpr->getType()->getPointeeType(); 1341 CVRQualifiers = ObjectTy.getCVRQualifiers(); 1342 } else { 1343 LValue BaseLV = EmitLValue(BaseExpr); 1344 // FIXME: this isn't right for bitfields. 1345 BaseValue = BaseLV.getAddress(); 1346 ObjectTy = BaseExpr->getType(); 1347 CVRQualifiers = ObjectTy.getCVRQualifiers(); 1348 } 1349 1350 return EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(), CVRQualifiers); 1351 } 1352 1353 LValue 1354 CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) { 1355 // This is a special l-value that just issues sends when we load or 1356 // store through it. 1357 return LValue::MakePropertyRef(E, E->getType().getCVRQualifiers()); 1358 } 1359 1360 LValue 1361 CodeGenFunction::EmitObjCKVCRefLValue( 1362 const ObjCImplicitSetterGetterRefExpr *E) { 1363 // This is a special l-value that just issues sends when we load or 1364 // store through it. 1365 return LValue::MakeKVCRef(E, E->getType().getCVRQualifiers()); 1366 } 1367 1368 LValue 1369 CodeGenFunction::EmitObjCSuperExprLValue(const ObjCSuperExpr *E) { 1370 return EmitUnsupportedLValue(E, "use of super"); 1371 } 1372 1373 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) { 1374 1375 // Can only get l-value for message expression returning aggregate type 1376 RValue RV = EmitAnyExprToTemp(E); 1377 // FIXME: can this be volatile? 1378 return LValue::MakeAddr(RV.getAggregateAddr(), 1379 E->getType().getCVRQualifiers(), 1380 getContext().getObjCGCAttrKind(E->getType()), 1381 E->getType().getAddressSpace()); 1382 } 1383 1384 1385 RValue CodeGenFunction::EmitCall(llvm::Value *Callee, QualType CalleeType, 1386 CallExpr::const_arg_iterator ArgBeg, 1387 CallExpr::const_arg_iterator ArgEnd, 1388 const Decl *TargetDecl) { 1389 // Get the actual function type. The callee type will always be a 1390 // pointer to function type or a block pointer type. 1391 assert(CalleeType->isFunctionPointerType() && 1392 "Call must have function pointer type!"); 1393 1394 QualType FnType = CalleeType->getAs<PointerType>()->getPointeeType(); 1395 QualType ResultType = FnType->getAsFunctionType()->getResultType(); 1396 1397 CallArgList Args; 1398 EmitCallArgs(Args, FnType->getAsFunctionProtoType(), ArgBeg, ArgEnd); 1399 1400 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args), 1401 Callee, Args, TargetDecl); 1402 } 1403