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 "CGCXXABI.h" 18 #include "CGRecordLayout.h" 19 #include "CGObjCRuntime.h" 20 #include "clang/AST/ASTContext.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "llvm/Intrinsics.h" 23 #include "clang/Frontend/CodeGenOptions.h" 24 #include "llvm/Target/TargetData.h" 25 using namespace clang; 26 using namespace CodeGen; 27 28 //===--------------------------------------------------------------------===// 29 // Miscellaneous Helper Methods 30 //===--------------------------------------------------------------------===// 31 32 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 33 /// block. 34 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty, 35 const llvm::Twine &Name) { 36 if (!Builder.isNamePreserving()) 37 return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt); 38 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt); 39 } 40 41 void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var, 42 llvm::Value *Init) { 43 llvm::StoreInst *Store = new llvm::StoreInst(Init, Var); 44 llvm::BasicBlock *Block = AllocaInsertPt->getParent(); 45 Block->getInstList().insertAfter(&*AllocaInsertPt, Store); 46 } 47 48 llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty, 49 const llvm::Twine &Name) { 50 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name); 51 // FIXME: Should we prefer the preferred type alignment here? 52 CharUnits Align = getContext().getTypeAlignInChars(Ty); 53 Alloc->setAlignment(Align.getQuantity()); 54 return Alloc; 55 } 56 57 llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty, 58 const llvm::Twine &Name) { 59 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name); 60 // FIXME: Should we prefer the preferred type alignment here? 61 CharUnits Align = getContext().getTypeAlignInChars(Ty); 62 Alloc->setAlignment(Align.getQuantity()); 63 return Alloc; 64 } 65 66 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 67 /// expression and compare the result against zero, returning an Int1Ty value. 68 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) { 69 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) { 70 llvm::Value *MemPtr = EmitScalarExpr(E); 71 return CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT); 72 } 73 74 QualType BoolTy = getContext().BoolTy; 75 if (!E->getType()->isAnyComplexType()) 76 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy); 77 78 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy); 79 } 80 81 /// EmitAnyExpr - Emit code to compute the specified expression which 82 /// can have any type. The result is returned as an RValue struct. 83 /// If this is an aggregate expression, AggSlot indicates where the 84 /// result should be returned. 85 RValue CodeGenFunction::EmitAnyExpr(const Expr *E, AggValueSlot AggSlot, 86 bool IgnoreResult) { 87 if (!hasAggregateLLVMType(E->getType())) 88 return RValue::get(EmitScalarExpr(E, IgnoreResult)); 89 else if (E->getType()->isAnyComplexType()) 90 return RValue::getComplex(EmitComplexExpr(E, false, false, 91 IgnoreResult, IgnoreResult)); 92 93 EmitAggExpr(E, AggSlot, IgnoreResult); 94 return AggSlot.asRValue(); 95 } 96 97 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 98 /// always be accessible even if no aggregate location is provided. 99 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) { 100 AggValueSlot AggSlot = AggValueSlot::ignored(); 101 102 if (hasAggregateLLVMType(E->getType()) && 103 !E->getType()->isAnyComplexType()) 104 AggSlot = CreateAggTemp(E->getType(), "agg.tmp"); 105 return EmitAnyExpr(E, AggSlot); 106 } 107 108 /// EmitAnyExprToMem - Evaluate an expression into a given memory 109 /// location. 110 void CodeGenFunction::EmitAnyExprToMem(const Expr *E, 111 llvm::Value *Location, 112 bool IsLocationVolatile, 113 bool IsInit) { 114 if (E->getType()->isComplexType()) 115 EmitComplexExprIntoAddr(E, Location, IsLocationVolatile); 116 else if (hasAggregateLLVMType(E->getType())) 117 EmitAggExpr(E, AggValueSlot::forAddr(Location, IsLocationVolatile, IsInit)); 118 else { 119 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false)); 120 LValue LV = MakeAddrLValue(Location, E->getType()); 121 EmitStoreThroughLValue(RV, LV, E->getType()); 122 } 123 } 124 125 /// \brief An adjustment to be made to the temporary created when emitting a 126 /// reference binding, which accesses a particular subobject of that temporary. 127 struct SubobjectAdjustment { 128 enum { DerivedToBaseAdjustment, FieldAdjustment } Kind; 129 130 union { 131 struct { 132 const CastExpr *BasePath; 133 const CXXRecordDecl *DerivedClass; 134 } DerivedToBase; 135 136 FieldDecl *Field; 137 }; 138 139 SubobjectAdjustment(const CastExpr *BasePath, 140 const CXXRecordDecl *DerivedClass) 141 : Kind(DerivedToBaseAdjustment) 142 { 143 DerivedToBase.BasePath = BasePath; 144 DerivedToBase.DerivedClass = DerivedClass; 145 } 146 147 SubobjectAdjustment(FieldDecl *Field) 148 : Kind(FieldAdjustment) 149 { 150 this->Field = Field; 151 } 152 }; 153 154 static llvm::Value * 155 CreateReferenceTemporary(CodeGenFunction& CGF, QualType Type, 156 const NamedDecl *InitializedDecl) { 157 if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) { 158 if (VD->hasGlobalStorage()) { 159 llvm::SmallString<256> Name; 160 CGF.CGM.getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Name); 161 162 const llvm::Type *RefTempTy = CGF.ConvertTypeForMem(Type); 163 164 // Create the reference temporary. 165 llvm::GlobalValue *RefTemp = 166 new llvm::GlobalVariable(CGF.CGM.getModule(), 167 RefTempTy, /*isConstant=*/false, 168 llvm::GlobalValue::InternalLinkage, 169 llvm::Constant::getNullValue(RefTempTy), 170 Name.str()); 171 return RefTemp; 172 } 173 } 174 175 return CGF.CreateMemTemp(Type, "ref.tmp"); 176 } 177 178 static llvm::Value * 179 EmitExprForReferenceBinding(CodeGenFunction &CGF, const Expr *E, 180 llvm::Value *&ReferenceTemporary, 181 const CXXDestructorDecl *&ReferenceTemporaryDtor, 182 const NamedDecl *InitializedDecl) { 183 if (const CXXDefaultArgExpr *DAE = dyn_cast<CXXDefaultArgExpr>(E)) 184 E = DAE->getExpr(); 185 186 if (const CXXExprWithTemporaries *TE = dyn_cast<CXXExprWithTemporaries>(E)) { 187 CodeGenFunction::RunCleanupsScope Scope(CGF); 188 189 return EmitExprForReferenceBinding(CGF, TE->getSubExpr(), 190 ReferenceTemporary, 191 ReferenceTemporaryDtor, 192 InitializedDecl); 193 } 194 195 RValue RV; 196 if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid) { 197 // Emit the expression as an lvalue. 198 LValue LV = CGF.EmitLValue(E); 199 if (LV.isPropertyRef() || LV.isKVCRef()) { 200 QualType QT = E->getType(); 201 RValue RV = 202 LV.isPropertyRef() ? CGF.EmitLoadOfPropertyRefLValue(LV, QT) 203 : CGF.EmitLoadOfKVCRefLValue(LV, QT); 204 assert(RV.isScalar() && "EmitExprForReferenceBinding"); 205 return RV.getScalarVal(); 206 } 207 208 if (LV.isSimple()) 209 return LV.getAddress(); 210 211 // We have to load the lvalue. 212 RV = CGF.EmitLoadOfLValue(LV, E->getType()); 213 } else { 214 QualType ResultTy = E->getType(); 215 216 llvm::SmallVector<SubobjectAdjustment, 2> Adjustments; 217 while (true) { 218 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 219 E = PE->getSubExpr(); 220 continue; 221 } 222 223 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 224 if ((CE->getCastKind() == CK_DerivedToBase || 225 CE->getCastKind() == CK_UncheckedDerivedToBase) && 226 E->getType()->isRecordType()) { 227 E = CE->getSubExpr(); 228 CXXRecordDecl *Derived 229 = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl()); 230 Adjustments.push_back(SubobjectAdjustment(CE, Derived)); 231 continue; 232 } 233 234 if (CE->getCastKind() == CK_NoOp) { 235 E = CE->getSubExpr(); 236 continue; 237 } 238 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 239 if (ME->getBase()->isLvalue(CGF.getContext()) != Expr::LV_Valid && 240 ME->getBase()->getType()->isRecordType()) { 241 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 242 E = ME->getBase(); 243 Adjustments.push_back(SubobjectAdjustment(Field)); 244 continue; 245 } 246 } 247 } 248 249 // Nothing changed. 250 break; 251 } 252 253 // Create a reference temporary if necessary. 254 AggValueSlot AggSlot = AggValueSlot::ignored(); 255 if (CGF.hasAggregateLLVMType(E->getType()) && 256 !E->getType()->isAnyComplexType()) { 257 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(), 258 InitializedDecl); 259 AggSlot = AggValueSlot::forAddr(ReferenceTemporary, false, 260 InitializedDecl != 0); 261 } 262 263 RV = CGF.EmitAnyExpr(E, AggSlot); 264 265 if (InitializedDecl) { 266 // Get the destructor for the reference temporary. 267 if (const RecordType *RT = E->getType()->getAs<RecordType>()) { 268 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 269 if (!ClassDecl->hasTrivialDestructor()) 270 ReferenceTemporaryDtor = ClassDecl->getDestructor(); 271 } 272 } 273 274 // Check if need to perform derived-to-base casts and/or field accesses, to 275 // get from the temporary object we created (and, potentially, for which we 276 // extended the lifetime) to the subobject we're binding the reference to. 277 if (!Adjustments.empty()) { 278 llvm::Value *Object = RV.getAggregateAddr(); 279 for (unsigned I = Adjustments.size(); I != 0; --I) { 280 SubobjectAdjustment &Adjustment = Adjustments[I-1]; 281 switch (Adjustment.Kind) { 282 case SubobjectAdjustment::DerivedToBaseAdjustment: 283 Object = 284 CGF.GetAddressOfBaseClass(Object, 285 Adjustment.DerivedToBase.DerivedClass, 286 Adjustment.DerivedToBase.BasePath->path_begin(), 287 Adjustment.DerivedToBase.BasePath->path_end(), 288 /*NullCheckValue=*/false); 289 break; 290 291 case SubobjectAdjustment::FieldAdjustment: { 292 LValue LV = 293 CGF.EmitLValueForField(Object, Adjustment.Field, 0); 294 if (LV.isSimple()) { 295 Object = LV.getAddress(); 296 break; 297 } 298 299 // For non-simple lvalues, we actually have to create a copy of 300 // the object we're binding to. 301 QualType T = Adjustment.Field->getType().getNonReferenceType() 302 .getUnqualifiedType(); 303 Object = CreateReferenceTemporary(CGF, T, InitializedDecl); 304 LValue TempLV = CGF.MakeAddrLValue(Object, 305 Adjustment.Field->getType()); 306 CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV, T), TempLV, T); 307 break; 308 } 309 310 } 311 } 312 313 const llvm::Type *ResultPtrTy = CGF.ConvertType(ResultTy)->getPointerTo(); 314 return CGF.Builder.CreateBitCast(Object, ResultPtrTy, "temp"); 315 } 316 } 317 318 if (RV.isAggregate()) 319 return RV.getAggregateAddr(); 320 321 // Create a temporary variable that we can bind the reference to. 322 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(), 323 InitializedDecl); 324 325 326 unsigned Alignment = 327 CGF.getContext().getTypeAlignInChars(E->getType()).getQuantity(); 328 if (RV.isScalar()) 329 CGF.EmitStoreOfScalar(RV.getScalarVal(), ReferenceTemporary, 330 /*Volatile=*/false, Alignment, E->getType()); 331 else 332 CGF.StoreComplexToAddr(RV.getComplexVal(), ReferenceTemporary, 333 /*Volatile=*/false); 334 return ReferenceTemporary; 335 } 336 337 RValue 338 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E, 339 const NamedDecl *InitializedDecl) { 340 llvm::Value *ReferenceTemporary = 0; 341 const CXXDestructorDecl *ReferenceTemporaryDtor = 0; 342 llvm::Value *Value = EmitExprForReferenceBinding(*this, E, ReferenceTemporary, 343 ReferenceTemporaryDtor, 344 InitializedDecl); 345 if (!ReferenceTemporaryDtor) 346 return RValue::get(Value); 347 348 // Make sure to call the destructor for the reference temporary. 349 if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) { 350 if (VD->hasGlobalStorage()) { 351 llvm::Constant *DtorFn = 352 CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete); 353 CGF.EmitCXXGlobalDtorRegistration(DtorFn, 354 cast<llvm::Constant>(ReferenceTemporary)); 355 356 return RValue::get(Value); 357 } 358 } 359 360 PushDestructorCleanup(ReferenceTemporaryDtor, ReferenceTemporary); 361 362 return RValue::get(Value); 363 } 364 365 366 /// getAccessedFieldNo - Given an encoded value and a result number, return the 367 /// input field number being accessed. 368 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx, 369 const llvm::Constant *Elts) { 370 if (isa<llvm::ConstantAggregateZero>(Elts)) 371 return 0; 372 373 return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue(); 374 } 375 376 void CodeGenFunction::EmitCheck(llvm::Value *Address, unsigned Size) { 377 if (!CatchUndefined) 378 return; 379 380 Address = Builder.CreateBitCast(Address, PtrToInt8Ty); 381 382 const llvm::Type *IntPtrT = IntPtrTy; 383 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, &IntPtrT, 1); 384 const llvm::IntegerType *Int1Ty = llvm::Type::getInt1Ty(VMContext); 385 386 // In time, people may want to control this and use a 1 here. 387 llvm::Value *Arg = llvm::ConstantInt::get(Int1Ty, 0); 388 llvm::Value *C = Builder.CreateCall2(F, Address, Arg); 389 llvm::BasicBlock *Cont = createBasicBlock(); 390 llvm::BasicBlock *Check = createBasicBlock(); 391 llvm::Value *NegativeOne = llvm::ConstantInt::get(IntPtrTy, -1ULL); 392 Builder.CreateCondBr(Builder.CreateICmpEQ(C, NegativeOne), Cont, Check); 393 394 EmitBlock(Check); 395 Builder.CreateCondBr(Builder.CreateICmpUGE(C, 396 llvm::ConstantInt::get(IntPtrTy, Size)), 397 Cont, getTrapBB()); 398 EmitBlock(Cont); 399 } 400 401 402 CodeGenFunction::ComplexPairTy CodeGenFunction:: 403 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 404 bool isInc, bool isPre) { 405 ComplexPairTy InVal = LoadComplexFromAddr(LV.getAddress(), 406 LV.isVolatileQualified()); 407 408 llvm::Value *NextVal; 409 if (isa<llvm::IntegerType>(InVal.first->getType())) { 410 uint64_t AmountVal = isInc ? 1 : -1; 411 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true); 412 413 // Add the inc/dec to the real part. 414 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec"); 415 } else { 416 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType(); 417 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1); 418 if (!isInc) 419 FVal.changeSign(); 420 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal); 421 422 // Add the inc/dec to the real part. 423 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec"); 424 } 425 426 ComplexPairTy IncVal(NextVal, InVal.second); 427 428 // Store the updated result through the lvalue. 429 StoreComplexToAddr(IncVal, LV.getAddress(), LV.isVolatileQualified()); 430 431 // If this is a postinc, return the value read from memory, otherwise use the 432 // updated value. 433 return isPre ? IncVal : InVal; 434 } 435 436 437 //===----------------------------------------------------------------------===// 438 // LValue Expression Emission 439 //===----------------------------------------------------------------------===// 440 441 RValue CodeGenFunction::GetUndefRValue(QualType Ty) { 442 if (Ty->isVoidType()) 443 return RValue::get(0); 444 445 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 446 const llvm::Type *EltTy = ConvertType(CTy->getElementType()); 447 llvm::Value *U = llvm::UndefValue::get(EltTy); 448 return RValue::getComplex(std::make_pair(U, U)); 449 } 450 451 // If this is a use of an undefined aggregate type, the aggregate must have an 452 // identifiable address. Just because the contents of the value are undefined 453 // doesn't mean that the address can't be taken and compared. 454 if (hasAggregateLLVMType(Ty)) { 455 llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp"); 456 return RValue::getAggregate(DestPtr); 457 } 458 459 return RValue::get(llvm::UndefValue::get(ConvertType(Ty))); 460 } 461 462 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E, 463 const char *Name) { 464 ErrorUnsupported(E, Name); 465 return GetUndefRValue(E->getType()); 466 } 467 468 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E, 469 const char *Name) { 470 ErrorUnsupported(E, Name); 471 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType())); 472 return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType()); 473 } 474 475 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E) { 476 LValue LV = EmitLValue(E); 477 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) 478 EmitCheck(LV.getAddress(), getContext().getTypeSize(E->getType()) / 8); 479 return LV; 480 } 481 482 /// EmitLValue - Emit code to compute a designator that specifies the location 483 /// of the expression. 484 /// 485 /// This can return one of two things: a simple address or a bitfield reference. 486 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be 487 /// an LLVM pointer type. 488 /// 489 /// If this returns a bitfield reference, nothing about the pointee type of the 490 /// LLVM value is known: For example, it may not be a pointer to an integer. 491 /// 492 /// If this returns a normal address, and if the lvalue's C type is fixed size, 493 /// this method guarantees that the returned pointer type will point to an LLVM 494 /// type of the same size of the lvalue's type. If the lvalue has a variable 495 /// length type, this is not possible. 496 /// 497 LValue CodeGenFunction::EmitLValue(const Expr *E) { 498 llvm::DenseMap<const Expr *, LValue>::iterator I = 499 CGF.ConditionalSaveLValueExprs.find(E); 500 if (I != CGF.ConditionalSaveLValueExprs.end()) 501 return I->second; 502 503 switch (E->getStmtClass()) { 504 default: return EmitUnsupportedLValue(E, "l-value expression"); 505 506 case Expr::ObjCSelectorExprClass: 507 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E)); 508 case Expr::ObjCIsaExprClass: 509 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E)); 510 case Expr::BinaryOperatorClass: 511 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E)); 512 case Expr::CompoundAssignOperatorClass: 513 return EmitCompoundAssignOperatorLValue(cast<CompoundAssignOperator>(E)); 514 case Expr::CallExprClass: 515 case Expr::CXXMemberCallExprClass: 516 case Expr::CXXOperatorCallExprClass: 517 return EmitCallExprLValue(cast<CallExpr>(E)); 518 case Expr::VAArgExprClass: 519 return EmitVAArgExprLValue(cast<VAArgExpr>(E)); 520 case Expr::DeclRefExprClass: 521 return EmitDeclRefLValue(cast<DeclRefExpr>(E)); 522 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr()); 523 case Expr::PredefinedExprClass: 524 return EmitPredefinedLValue(cast<PredefinedExpr>(E)); 525 case Expr::StringLiteralClass: 526 return EmitStringLiteralLValue(cast<StringLiteral>(E)); 527 case Expr::ObjCEncodeExprClass: 528 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E)); 529 530 case Expr::BlockDeclRefExprClass: 531 return EmitBlockDeclRefLValue(cast<BlockDeclRefExpr>(E)); 532 533 case Expr::CXXTemporaryObjectExprClass: 534 case Expr::CXXConstructExprClass: 535 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E)); 536 case Expr::CXXBindTemporaryExprClass: 537 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E)); 538 case Expr::CXXExprWithTemporariesClass: 539 return EmitCXXExprWithTemporariesLValue(cast<CXXExprWithTemporaries>(E)); 540 case Expr::CXXScalarValueInitExprClass: 541 return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E)); 542 case Expr::CXXDefaultArgExprClass: 543 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr()); 544 case Expr::CXXTypeidExprClass: 545 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E)); 546 547 case Expr::ObjCMessageExprClass: 548 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E)); 549 case Expr::ObjCIvarRefExprClass: 550 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E)); 551 case Expr::ObjCPropertyRefExprClass: 552 return EmitObjCPropertyRefLValue(cast<ObjCPropertyRefExpr>(E)); 553 case Expr::ObjCImplicitSetterGetterRefExprClass: 554 return EmitObjCKVCRefLValue(cast<ObjCImplicitSetterGetterRefExpr>(E)); 555 case Expr::StmtExprClass: 556 return EmitStmtExprLValue(cast<StmtExpr>(E)); 557 case Expr::UnaryOperatorClass: 558 return EmitUnaryOpLValue(cast<UnaryOperator>(E)); 559 case Expr::ArraySubscriptExprClass: 560 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E)); 561 case Expr::ExtVectorElementExprClass: 562 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E)); 563 case Expr::MemberExprClass: 564 return EmitMemberExpr(cast<MemberExpr>(E)); 565 case Expr::CompoundLiteralExprClass: 566 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E)); 567 case Expr::ConditionalOperatorClass: 568 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E)); 569 case Expr::ChooseExprClass: 570 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext())); 571 case Expr::ImplicitCastExprClass: 572 case Expr::CStyleCastExprClass: 573 case Expr::CXXFunctionalCastExprClass: 574 case Expr::CXXStaticCastExprClass: 575 case Expr::CXXDynamicCastExprClass: 576 case Expr::CXXReinterpretCastExprClass: 577 case Expr::CXXConstCastExprClass: 578 return EmitCastLValue(cast<CastExpr>(E)); 579 } 580 } 581 582 llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile, 583 unsigned Alignment, QualType Ty, 584 llvm::MDNode *TBAAInfo) { 585 llvm::LoadInst *Load = Builder.CreateLoad(Addr, "tmp"); 586 if (Volatile) 587 Load->setVolatile(true); 588 if (Alignment) 589 Load->setAlignment(Alignment); 590 if (TBAAInfo) 591 CGM.DecorateInstruction(Load, TBAAInfo); 592 593 return EmitFromMemory(Load, Ty); 594 } 595 596 static bool isBooleanUnderlyingType(QualType Ty) { 597 if (const EnumType *ET = dyn_cast<EnumType>(Ty)) 598 return ET->getDecl()->getIntegerType()->isBooleanType(); 599 return false; 600 } 601 602 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) { 603 // Bool has a different representation in memory than in registers. 604 if (Ty->isBooleanType() || isBooleanUnderlyingType(Ty)) { 605 assert(Value->getType()->isIntegerTy(1) && "value rep of bool not i1"); 606 return Builder.CreateZExt(Value, Builder.getInt8Ty(), "frombool"); 607 } 608 609 return Value; 610 } 611 612 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) { 613 // Bool has a different representation in memory than in registers. 614 if (Ty->isBooleanType() || isBooleanUnderlyingType(Ty)) { 615 assert(Value->getType()->isIntegerTy(8) && "memory rep of bool not i8"); 616 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool"); 617 } 618 619 return Value; 620 } 621 622 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr, 623 bool Volatile, unsigned Alignment, 624 QualType Ty, 625 llvm::MDNode *TBAAInfo) { 626 Value = EmitToMemory(Value, Ty); 627 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile); 628 if (Alignment) 629 Store->setAlignment(Alignment); 630 if (TBAAInfo) 631 CGM.DecorateInstruction(Store, TBAAInfo); 632 } 633 634 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this 635 /// method emits the address of the lvalue, then loads the result as an rvalue, 636 /// returning the rvalue. 637 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) { 638 if (LV.isObjCWeak()) { 639 // load of a __weak object. 640 llvm::Value *AddrWeakObj = LV.getAddress(); 641 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this, 642 AddrWeakObj)); 643 } 644 645 if (LV.isSimple()) { 646 llvm::Value *Ptr = LV.getAddress(); 647 648 // Functions are l-values that don't require loading. 649 if (ExprType->isFunctionType()) 650 return RValue::get(Ptr); 651 652 // Everything needs a load. 653 return RValue::get(EmitLoadOfScalar(Ptr, LV.isVolatileQualified(), 654 LV.getAlignment(), ExprType, 655 LV.getTBAAInfo())); 656 657 } 658 659 if (LV.isVectorElt()) { 660 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), 661 LV.isVolatileQualified(), "tmp"); 662 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(), 663 "vecext")); 664 } 665 666 // If this is a reference to a subset of the elements of a vector, either 667 // shuffle the input or extract/insert them as appropriate. 668 if (LV.isExtVectorElt()) 669 return EmitLoadOfExtVectorElementLValue(LV, ExprType); 670 671 if (LV.isBitField()) 672 return EmitLoadOfBitfieldLValue(LV, ExprType); 673 674 if (LV.isPropertyRef()) 675 return EmitLoadOfPropertyRefLValue(LV, ExprType); 676 677 assert(LV.isKVCRef() && "Unknown LValue type!"); 678 return EmitLoadOfKVCRefLValue(LV, ExprType); 679 } 680 681 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV, 682 QualType ExprType) { 683 const CGBitFieldInfo &Info = LV.getBitFieldInfo(); 684 685 // Get the output type. 686 const llvm::Type *ResLTy = ConvertType(ExprType); 687 unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy); 688 689 // Compute the result as an OR of all of the individual component accesses. 690 llvm::Value *Res = 0; 691 for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) { 692 const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i); 693 694 // Get the field pointer. 695 llvm::Value *Ptr = LV.getBitFieldBaseAddr(); 696 697 // Only offset by the field index if used, so that incoming values are not 698 // required to be structures. 699 if (AI.FieldIndex) 700 Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field"); 701 702 // Offset by the byte offset, if used. 703 if (AI.FieldByteOffset) { 704 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext); 705 Ptr = Builder.CreateBitCast(Ptr, i8PTy); 706 Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset,"bf.field.offs"); 707 } 708 709 // Cast to the access type. 710 const llvm::Type *PTy = llvm::Type::getIntNPtrTy(VMContext, AI.AccessWidth, 711 ExprType.getAddressSpace()); 712 Ptr = Builder.CreateBitCast(Ptr, PTy); 713 714 // Perform the load. 715 llvm::LoadInst *Load = Builder.CreateLoad(Ptr, LV.isVolatileQualified()); 716 if (AI.AccessAlignment) 717 Load->setAlignment(AI.AccessAlignment); 718 719 // Shift out unused low bits and mask out unused high bits. 720 llvm::Value *Val = Load; 721 if (AI.FieldBitStart) 722 Val = Builder.CreateLShr(Load, AI.FieldBitStart); 723 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(AI.AccessWidth, 724 AI.TargetBitWidth), 725 "bf.clear"); 726 727 // Extend or truncate to the target size. 728 if (AI.AccessWidth < ResSizeInBits) 729 Val = Builder.CreateZExt(Val, ResLTy); 730 else if (AI.AccessWidth > ResSizeInBits) 731 Val = Builder.CreateTrunc(Val, ResLTy); 732 733 // Shift into place, and OR into the result. 734 if (AI.TargetBitOffset) 735 Val = Builder.CreateShl(Val, AI.TargetBitOffset); 736 Res = Res ? Builder.CreateOr(Res, Val) : Val; 737 } 738 739 // If the bit-field is signed, perform the sign-extension. 740 // 741 // FIXME: This can easily be folded into the load of the high bits, which 742 // could also eliminate the mask of high bits in some situations. 743 if (Info.isSigned()) { 744 unsigned ExtraBits = ResSizeInBits - Info.getSize(); 745 if (ExtraBits) 746 Res = Builder.CreateAShr(Builder.CreateShl(Res, ExtraBits), 747 ExtraBits, "bf.val.sext"); 748 } 749 750 return RValue::get(Res); 751 } 752 753 RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV, 754 QualType ExprType) { 755 return EmitObjCPropertyGet(LV.getPropertyRefExpr()); 756 } 757 758 RValue CodeGenFunction::EmitLoadOfKVCRefLValue(LValue LV, 759 QualType ExprType) { 760 return EmitObjCPropertyGet(LV.getKVCRefExpr()); 761 } 762 763 // If this is a reference to a subset of the elements of a vector, create an 764 // appropriate shufflevector. 765 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV, 766 QualType ExprType) { 767 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(), 768 LV.isVolatileQualified(), "tmp"); 769 770 const llvm::Constant *Elts = LV.getExtVectorElts(); 771 772 // If the result of the expression is a non-vector type, we must be extracting 773 // a single element. Just codegen as an extractelement. 774 const VectorType *ExprVT = ExprType->getAs<VectorType>(); 775 if (!ExprVT) { 776 unsigned InIdx = getAccessedFieldNo(0, Elts); 777 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx); 778 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp")); 779 } 780 781 // Always use shuffle vector to try to retain the original program structure 782 unsigned NumResultElts = ExprVT->getNumElements(); 783 784 llvm::SmallVector<llvm::Constant*, 4> Mask; 785 for (unsigned i = 0; i != NumResultElts; ++i) { 786 unsigned InIdx = getAccessedFieldNo(i, Elts); 787 Mask.push_back(llvm::ConstantInt::get(Int32Ty, InIdx)); 788 } 789 790 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size()); 791 Vec = Builder.CreateShuffleVector(Vec, 792 llvm::UndefValue::get(Vec->getType()), 793 MaskV, "tmp"); 794 return RValue::get(Vec); 795 } 796 797 798 799 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 800 /// lvalue, where both are guaranteed to the have the same type, and that type 801 /// is 'Ty'. 802 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, 803 QualType Ty) { 804 if (!Dst.isSimple()) { 805 if (Dst.isVectorElt()) { 806 // Read/modify/write the vector, inserting the new element. 807 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), 808 Dst.isVolatileQualified(), "tmp"); 809 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(), 810 Dst.getVectorIdx(), "vecins"); 811 Builder.CreateStore(Vec, Dst.getVectorAddr(),Dst.isVolatileQualified()); 812 return; 813 } 814 815 // If this is an update of extended vector elements, insert them as 816 // appropriate. 817 if (Dst.isExtVectorElt()) 818 return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty); 819 820 if (Dst.isBitField()) 821 return EmitStoreThroughBitfieldLValue(Src, Dst, Ty); 822 823 if (Dst.isPropertyRef()) 824 return EmitStoreThroughPropertyRefLValue(Src, Dst, Ty); 825 826 assert(Dst.isKVCRef() && "Unknown LValue type"); 827 return EmitStoreThroughKVCRefLValue(Src, Dst, Ty); 828 } 829 830 if (Dst.isObjCWeak() && !Dst.isNonGC()) { 831 // load of a __weak object. 832 llvm::Value *LvalueDst = Dst.getAddress(); 833 llvm::Value *src = Src.getScalarVal(); 834 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst); 835 return; 836 } 837 838 if (Dst.isObjCStrong() && !Dst.isNonGC()) { 839 // load of a __strong object. 840 llvm::Value *LvalueDst = Dst.getAddress(); 841 llvm::Value *src = Src.getScalarVal(); 842 if (Dst.isObjCIvar()) { 843 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL"); 844 const llvm::Type *ResultType = ConvertType(getContext().LongTy); 845 llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp()); 846 llvm::Value *dst = RHS; 847 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast"); 848 llvm::Value *LHS = 849 Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast"); 850 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset"); 851 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst, 852 BytesBetween); 853 } else if (Dst.isGlobalObjCRef()) { 854 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst, 855 Dst.isThreadLocalRef()); 856 } 857 else 858 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst); 859 return; 860 } 861 862 assert(Src.isScalar() && "Can't emit an agg store with this method"); 863 EmitStoreOfScalar(Src.getScalarVal(), Dst.getAddress(), 864 Dst.isVolatileQualified(), Dst.getAlignment(), Ty, 865 Dst.getTBAAInfo()); 866 } 867 868 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 869 QualType Ty, 870 llvm::Value **Result) { 871 const CGBitFieldInfo &Info = Dst.getBitFieldInfo(); 872 873 // Get the output type. 874 const llvm::Type *ResLTy = ConvertTypeForMem(Ty); 875 unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy); 876 877 // Get the source value, truncated to the width of the bit-field. 878 llvm::Value *SrcVal = Src.getScalarVal(); 879 880 if (Ty->isBooleanType()) 881 SrcVal = Builder.CreateIntCast(SrcVal, ResLTy, /*IsSigned=*/false); 882 883 SrcVal = Builder.CreateAnd(SrcVal, llvm::APInt::getLowBitsSet(ResSizeInBits, 884 Info.getSize()), 885 "bf.value"); 886 887 // Return the new value of the bit-field, if requested. 888 if (Result) { 889 // Cast back to the proper type for result. 890 const llvm::Type *SrcTy = Src.getScalarVal()->getType(); 891 llvm::Value *ReloadVal = Builder.CreateIntCast(SrcVal, SrcTy, false, 892 "bf.reload.val"); 893 894 // Sign extend if necessary. 895 if (Info.isSigned()) { 896 unsigned ExtraBits = ResSizeInBits - Info.getSize(); 897 if (ExtraBits) 898 ReloadVal = Builder.CreateAShr(Builder.CreateShl(ReloadVal, ExtraBits), 899 ExtraBits, "bf.reload.sext"); 900 } 901 902 *Result = ReloadVal; 903 } 904 905 // Iterate over the components, writing each piece to memory. 906 for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) { 907 const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i); 908 909 // Get the field pointer. 910 llvm::Value *Ptr = Dst.getBitFieldBaseAddr(); 911 912 // Only offset by the field index if used, so that incoming values are not 913 // required to be structures. 914 if (AI.FieldIndex) 915 Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field"); 916 917 // Offset by the byte offset, if used. 918 if (AI.FieldByteOffset) { 919 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext); 920 Ptr = Builder.CreateBitCast(Ptr, i8PTy); 921 Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset,"bf.field.offs"); 922 } 923 924 // Cast to the access type. 925 const llvm::Type *PTy = llvm::Type::getIntNPtrTy(VMContext, AI.AccessWidth, 926 Ty.getAddressSpace()); 927 Ptr = Builder.CreateBitCast(Ptr, PTy); 928 929 // Extract the piece of the bit-field value to write in this access, limited 930 // to the values that are part of this access. 931 llvm::Value *Val = SrcVal; 932 if (AI.TargetBitOffset) 933 Val = Builder.CreateLShr(Val, AI.TargetBitOffset); 934 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(ResSizeInBits, 935 AI.TargetBitWidth)); 936 937 // Extend or truncate to the access size. 938 const llvm::Type *AccessLTy = 939 llvm::Type::getIntNTy(VMContext, AI.AccessWidth); 940 if (ResSizeInBits < AI.AccessWidth) 941 Val = Builder.CreateZExt(Val, AccessLTy); 942 else if (ResSizeInBits > AI.AccessWidth) 943 Val = Builder.CreateTrunc(Val, AccessLTy); 944 945 // Shift into the position in memory. 946 if (AI.FieldBitStart) 947 Val = Builder.CreateShl(Val, AI.FieldBitStart); 948 949 // If necessary, load and OR in bits that are outside of the bit-field. 950 if (AI.TargetBitWidth != AI.AccessWidth) { 951 llvm::LoadInst *Load = Builder.CreateLoad(Ptr, Dst.isVolatileQualified()); 952 if (AI.AccessAlignment) 953 Load->setAlignment(AI.AccessAlignment); 954 955 // Compute the mask for zeroing the bits that are part of the bit-field. 956 llvm::APInt InvMask = 957 ~llvm::APInt::getBitsSet(AI.AccessWidth, AI.FieldBitStart, 958 AI.FieldBitStart + AI.TargetBitWidth); 959 960 // Apply the mask and OR in to the value to write. 961 Val = Builder.CreateOr(Builder.CreateAnd(Load, InvMask), Val); 962 } 963 964 // Write the value. 965 llvm::StoreInst *Store = Builder.CreateStore(Val, Ptr, 966 Dst.isVolatileQualified()); 967 if (AI.AccessAlignment) 968 Store->setAlignment(AI.AccessAlignment); 969 } 970 } 971 972 void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src, 973 LValue Dst, 974 QualType Ty) { 975 EmitObjCPropertySet(Dst.getPropertyRefExpr(), Src); 976 } 977 978 void CodeGenFunction::EmitStoreThroughKVCRefLValue(RValue Src, 979 LValue Dst, 980 QualType Ty) { 981 EmitObjCPropertySet(Dst.getKVCRefExpr(), Src); 982 } 983 984 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src, 985 LValue Dst, 986 QualType Ty) { 987 // This access turns into a read/modify/write of the vector. Load the input 988 // value now. 989 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(), 990 Dst.isVolatileQualified(), "tmp"); 991 const llvm::Constant *Elts = Dst.getExtVectorElts(); 992 993 llvm::Value *SrcVal = Src.getScalarVal(); 994 995 if (const VectorType *VTy = Ty->getAs<VectorType>()) { 996 unsigned NumSrcElts = VTy->getNumElements(); 997 unsigned NumDstElts = 998 cast<llvm::VectorType>(Vec->getType())->getNumElements(); 999 if (NumDstElts == NumSrcElts) { 1000 // Use shuffle vector is the src and destination are the same number of 1001 // elements and restore the vector mask since it is on the side it will be 1002 // stored. 1003 llvm::SmallVector<llvm::Constant*, 4> Mask(NumDstElts); 1004 for (unsigned i = 0; i != NumSrcElts; ++i) { 1005 unsigned InIdx = getAccessedFieldNo(i, Elts); 1006 Mask[InIdx] = llvm::ConstantInt::get(Int32Ty, i); 1007 } 1008 1009 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size()); 1010 Vec = Builder.CreateShuffleVector(SrcVal, 1011 llvm::UndefValue::get(Vec->getType()), 1012 MaskV, "tmp"); 1013 } else if (NumDstElts > NumSrcElts) { 1014 // Extended the source vector to the same length and then shuffle it 1015 // into the destination. 1016 // FIXME: since we're shuffling with undef, can we just use the indices 1017 // into that? This could be simpler. 1018 llvm::SmallVector<llvm::Constant*, 4> ExtMask; 1019 unsigned i; 1020 for (i = 0; i != NumSrcElts; ++i) 1021 ExtMask.push_back(llvm::ConstantInt::get(Int32Ty, i)); 1022 for (; i != NumDstElts; ++i) 1023 ExtMask.push_back(llvm::UndefValue::get(Int32Ty)); 1024 llvm::Value *ExtMaskV = llvm::ConstantVector::get(&ExtMask[0], 1025 ExtMask.size()); 1026 llvm::Value *ExtSrcVal = 1027 Builder.CreateShuffleVector(SrcVal, 1028 llvm::UndefValue::get(SrcVal->getType()), 1029 ExtMaskV, "tmp"); 1030 // build identity 1031 llvm::SmallVector<llvm::Constant*, 4> Mask; 1032 for (unsigned i = 0; i != NumDstElts; ++i) 1033 Mask.push_back(llvm::ConstantInt::get(Int32Ty, i)); 1034 1035 // modify when what gets shuffled in 1036 for (unsigned i = 0; i != NumSrcElts; ++i) { 1037 unsigned Idx = getAccessedFieldNo(i, Elts); 1038 Mask[Idx] = llvm::ConstantInt::get(Int32Ty, i+NumDstElts); 1039 } 1040 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size()); 1041 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV, "tmp"); 1042 } else { 1043 // We should never shorten the vector 1044 assert(0 && "unexpected shorten vector length"); 1045 } 1046 } else { 1047 // If the Src is a scalar (not a vector) it must be updating one element. 1048 unsigned InIdx = getAccessedFieldNo(0, Elts); 1049 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx); 1050 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp"); 1051 } 1052 1053 Builder.CreateStore(Vec, Dst.getExtVectorAddr(), Dst.isVolatileQualified()); 1054 } 1055 1056 // setObjCGCLValueClass - sets class of he lvalue for the purpose of 1057 // generating write-barries API. It is currently a global, ivar, 1058 // or neither. 1059 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E, 1060 LValue &LV) { 1061 if (Ctx.getLangOptions().getGCMode() == LangOptions::NonGC) 1062 return; 1063 1064 if (isa<ObjCIvarRefExpr>(E)) { 1065 LV.setObjCIvar(true); 1066 ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E)); 1067 LV.setBaseIvarExp(Exp->getBase()); 1068 LV.setObjCArray(E->getType()->isArrayType()); 1069 return; 1070 } 1071 1072 if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) { 1073 if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) { 1074 if (VD->hasGlobalStorage()) { 1075 LV.setGlobalObjCRef(true); 1076 LV.setThreadLocalRef(VD->isThreadSpecified()); 1077 } 1078 } 1079 LV.setObjCArray(E->getType()->isArrayType()); 1080 return; 1081 } 1082 1083 if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) { 1084 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV); 1085 return; 1086 } 1087 1088 if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) { 1089 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV); 1090 if (LV.isObjCIvar()) { 1091 // If cast is to a structure pointer, follow gcc's behavior and make it 1092 // a non-ivar write-barrier. 1093 QualType ExpTy = E->getType(); 1094 if (ExpTy->isPointerType()) 1095 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType(); 1096 if (ExpTy->isRecordType()) 1097 LV.setObjCIvar(false); 1098 } 1099 return; 1100 } 1101 if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) { 1102 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV); 1103 return; 1104 } 1105 1106 if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) { 1107 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV); 1108 return; 1109 } 1110 1111 if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) { 1112 setObjCGCLValueClass(Ctx, Exp->getBase(), LV); 1113 if (LV.isObjCIvar() && !LV.isObjCArray()) 1114 // Using array syntax to assigning to what an ivar points to is not 1115 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0; 1116 LV.setObjCIvar(false); 1117 else if (LV.isGlobalObjCRef() && !LV.isObjCArray()) 1118 // Using array syntax to assigning to what global points to is not 1119 // same as assigning to the global itself. {id *G;} G[i] = 0; 1120 LV.setGlobalObjCRef(false); 1121 return; 1122 } 1123 1124 if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) { 1125 setObjCGCLValueClass(Ctx, Exp->getBase(), LV); 1126 // We don't know if member is an 'ivar', but this flag is looked at 1127 // only in the context of LV.isObjCIvar(). 1128 LV.setObjCArray(E->getType()->isArrayType()); 1129 return; 1130 } 1131 } 1132 1133 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF, 1134 const Expr *E, const VarDecl *VD) { 1135 assert((VD->hasExternalStorage() || VD->isFileVarDecl()) && 1136 "Var decl must have external storage or be a file var decl!"); 1137 1138 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD); 1139 if (VD->getType()->isReferenceType()) 1140 V = CGF.Builder.CreateLoad(V, "tmp"); 1141 unsigned Alignment = CGF.getContext().getDeclAlign(VD).getQuantity(); 1142 LValue LV = CGF.MakeAddrLValue(V, E->getType(), Alignment); 1143 setObjCGCLValueClass(CGF.getContext(), E, LV); 1144 return LV; 1145 } 1146 1147 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, 1148 const Expr *E, const FunctionDecl *FD) { 1149 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD); 1150 if (!FD->hasPrototype()) { 1151 if (const FunctionProtoType *Proto = 1152 FD->getType()->getAs<FunctionProtoType>()) { 1153 // Ugly case: for a K&R-style definition, the type of the definition 1154 // isn't the same as the type of a use. Correct for this with a 1155 // bitcast. 1156 QualType NoProtoType = 1157 CGF.getContext().getFunctionNoProtoType(Proto->getResultType()); 1158 NoProtoType = CGF.getContext().getPointerType(NoProtoType); 1159 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType), "tmp"); 1160 } 1161 } 1162 unsigned Alignment = CGF.getContext().getDeclAlign(FD).getQuantity(); 1163 return CGF.MakeAddrLValue(V, E->getType(), Alignment); 1164 } 1165 1166 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) { 1167 const NamedDecl *ND = E->getDecl(); 1168 unsigned Alignment = CGF.getContext().getDeclAlign(ND).getQuantity(); 1169 1170 if (ND->hasAttr<WeakRefAttr>()) { 1171 const ValueDecl *VD = cast<ValueDecl>(ND); 1172 llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD); 1173 return MakeAddrLValue(Aliasee, E->getType(), Alignment); 1174 } 1175 1176 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) { 1177 1178 // Check if this is a global variable. 1179 if (VD->hasExternalStorage() || VD->isFileVarDecl()) 1180 return EmitGlobalVarDeclLValue(*this, E, VD); 1181 1182 bool NonGCable = VD->hasLocalStorage() && !VD->hasAttr<BlocksAttr>(); 1183 1184 llvm::Value *V = LocalDeclMap[VD]; 1185 if (!V && VD->isStaticLocal()) 1186 V = CGM.getStaticLocalDeclAddress(VD); 1187 assert(V && "DeclRefExpr not entered in LocalDeclMap?"); 1188 1189 if (VD->hasAttr<BlocksAttr>()) { 1190 V = Builder.CreateStructGEP(V, 1, "forwarding"); 1191 V = Builder.CreateLoad(V); 1192 V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD), 1193 VD->getNameAsString()); 1194 } 1195 if (VD->getType()->isReferenceType()) 1196 V = Builder.CreateLoad(V, "tmp"); 1197 1198 LValue LV = MakeAddrLValue(V, E->getType(), Alignment); 1199 if (NonGCable) { 1200 LV.getQuals().removeObjCGCAttr(); 1201 LV.setNonGC(true); 1202 } 1203 setObjCGCLValueClass(getContext(), E, LV); 1204 return LV; 1205 } 1206 1207 // If we're emitting an instance method as an independent lvalue, 1208 // we're actually emitting a member pointer. 1209 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 1210 if (MD->isInstance()) { 1211 llvm::Value *V = CGM.getCXXABI().EmitMemberPointer(MD); 1212 return MakeAddrLValue(V, MD->getType(), Alignment); 1213 } 1214 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) 1215 return EmitFunctionDeclLValue(*this, E, FD); 1216 1217 // If we're emitting a field as an independent lvalue, we're 1218 // actually emitting a member pointer. 1219 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ND)) { 1220 llvm::Value *V = CGM.getCXXABI().EmitMemberPointer(FD); 1221 return MakeAddrLValue(V, FD->getType(), Alignment); 1222 } 1223 1224 assert(false && "Unhandled DeclRefExpr"); 1225 1226 // an invalid LValue, but the assert will 1227 // ensure that this point is never reached. 1228 return LValue(); 1229 } 1230 1231 LValue CodeGenFunction::EmitBlockDeclRefLValue(const BlockDeclRefExpr *E) { 1232 unsigned Alignment = 1233 CGF.getContext().getDeclAlign(E->getDecl()).getQuantity(); 1234 return MakeAddrLValue(GetAddrOfBlockDecl(E), E->getType(), Alignment); 1235 } 1236 1237 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) { 1238 // __extension__ doesn't affect lvalue-ness. 1239 if (E->getOpcode() == UO_Extension) 1240 return EmitLValue(E->getSubExpr()); 1241 1242 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType()); 1243 switch (E->getOpcode()) { 1244 default: assert(0 && "Unknown unary operator lvalue!"); 1245 case UO_Deref: { 1246 QualType T = E->getSubExpr()->getType()->getPointeeType(); 1247 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type"); 1248 1249 LValue LV = MakeAddrLValue(EmitScalarExpr(E->getSubExpr()), T); 1250 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace()); 1251 1252 // We should not generate __weak write barrier on indirect reference 1253 // of a pointer to object; as in void foo (__weak id *param); *param = 0; 1254 // But, we continue to generate __strong write barrier on indirect write 1255 // into a pointer to object. 1256 if (getContext().getLangOptions().ObjC1 && 1257 getContext().getLangOptions().getGCMode() != LangOptions::NonGC && 1258 LV.isObjCWeak()) 1259 LV.setNonGC(!E->isOBJCGCCandidate(getContext())); 1260 return LV; 1261 } 1262 case UO_Real: 1263 case UO_Imag: { 1264 LValue LV = EmitLValue(E->getSubExpr()); 1265 unsigned Idx = E->getOpcode() == UO_Imag; 1266 return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(), 1267 Idx, "idx"), 1268 ExprTy); 1269 } 1270 case UO_PreInc: 1271 case UO_PreDec: { 1272 LValue LV = EmitLValue(E->getSubExpr()); 1273 bool isInc = E->getOpcode() == UO_PreInc; 1274 1275 if (E->getType()->isAnyComplexType()) 1276 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/); 1277 else 1278 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/); 1279 return LV; 1280 } 1281 } 1282 } 1283 1284 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) { 1285 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E), 1286 E->getType()); 1287 } 1288 1289 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) { 1290 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E), 1291 E->getType()); 1292 } 1293 1294 1295 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) { 1296 switch (E->getIdentType()) { 1297 default: 1298 return EmitUnsupportedLValue(E, "predefined expression"); 1299 1300 case PredefinedExpr::Func: 1301 case PredefinedExpr::Function: 1302 case PredefinedExpr::PrettyFunction: { 1303 unsigned Type = E->getIdentType(); 1304 std::string GlobalVarName; 1305 1306 switch (Type) { 1307 default: assert(0 && "Invalid type"); 1308 case PredefinedExpr::Func: 1309 GlobalVarName = "__func__."; 1310 break; 1311 case PredefinedExpr::Function: 1312 GlobalVarName = "__FUNCTION__."; 1313 break; 1314 case PredefinedExpr::PrettyFunction: 1315 GlobalVarName = "__PRETTY_FUNCTION__."; 1316 break; 1317 } 1318 1319 llvm::StringRef FnName = CurFn->getName(); 1320 if (FnName.startswith("\01")) 1321 FnName = FnName.substr(1); 1322 GlobalVarName += FnName; 1323 1324 const Decl *CurDecl = CurCodeDecl; 1325 if (CurDecl == 0) 1326 CurDecl = getContext().getTranslationUnitDecl(); 1327 1328 std::string FunctionName = 1329 PredefinedExpr::ComputeName((PredefinedExpr::IdentType)Type, CurDecl); 1330 1331 llvm::Constant *C = 1332 CGM.GetAddrOfConstantCString(FunctionName, GlobalVarName.c_str()); 1333 return MakeAddrLValue(C, E->getType()); 1334 } 1335 } 1336 } 1337 1338 llvm::BasicBlock *CodeGenFunction::getTrapBB() { 1339 const CodeGenOptions &GCO = CGM.getCodeGenOpts(); 1340 1341 // If we are not optimzing, don't collapse all calls to trap in the function 1342 // to the same call, that way, in the debugger they can see which operation 1343 // did in fact fail. If we are optimizing, we collapse all calls to trap down 1344 // to just one per function to save on codesize. 1345 if (GCO.OptimizationLevel && TrapBB) 1346 return TrapBB; 1347 1348 llvm::BasicBlock *Cont = 0; 1349 if (HaveInsertPoint()) { 1350 Cont = createBasicBlock("cont"); 1351 EmitBranch(Cont); 1352 } 1353 TrapBB = createBasicBlock("trap"); 1354 EmitBlock(TrapBB); 1355 1356 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap, 0, 0); 1357 llvm::CallInst *TrapCall = Builder.CreateCall(F); 1358 TrapCall->setDoesNotReturn(); 1359 TrapCall->setDoesNotThrow(); 1360 Builder.CreateUnreachable(); 1361 1362 if (Cont) 1363 EmitBlock(Cont); 1364 return TrapBB; 1365 } 1366 1367 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an 1368 /// array to pointer, return the array subexpression. 1369 static const Expr *isSimpleArrayDecayOperand(const Expr *E) { 1370 // If this isn't just an array->pointer decay, bail out. 1371 const CastExpr *CE = dyn_cast<CastExpr>(E); 1372 if (CE == 0 || CE->getCastKind() != CK_ArrayToPointerDecay) 1373 return 0; 1374 1375 // If this is a decay from variable width array, bail out. 1376 const Expr *SubExpr = CE->getSubExpr(); 1377 if (SubExpr->getType()->isVariableArrayType()) 1378 return 0; 1379 1380 return SubExpr; 1381 } 1382 1383 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) { 1384 // The index must always be an integer, which is not an aggregate. Emit it. 1385 llvm::Value *Idx = EmitScalarExpr(E->getIdx()); 1386 QualType IdxTy = E->getIdx()->getType(); 1387 bool IdxSigned = IdxTy->isSignedIntegerType(); 1388 1389 // If the base is a vector type, then we are forming a vector element lvalue 1390 // with this subscript. 1391 if (E->getBase()->getType()->isVectorType()) { 1392 // Emit the vector as an lvalue to get its address. 1393 LValue LHS = EmitLValue(E->getBase()); 1394 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!"); 1395 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vidx"); 1396 return LValue::MakeVectorElt(LHS.getAddress(), Idx, 1397 E->getBase()->getType().getCVRQualifiers()); 1398 } 1399 1400 // Extend or truncate the index type to 32 or 64-bits. 1401 if (!Idx->getType()->isIntegerTy(LLVMPointerWidth)) 1402 Idx = Builder.CreateIntCast(Idx, IntPtrTy, 1403 IdxSigned, "idxprom"); 1404 1405 // FIXME: As llvm implements the object size checking, this can come out. 1406 if (CatchUndefined) { 1407 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E->getBase())){ 1408 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) { 1409 if (ICE->getCastKind() == CK_ArrayToPointerDecay) { 1410 if (const ConstantArrayType *CAT 1411 = getContext().getAsConstantArrayType(DRE->getType())) { 1412 llvm::APInt Size = CAT->getSize(); 1413 llvm::BasicBlock *Cont = createBasicBlock("cont"); 1414 Builder.CreateCondBr(Builder.CreateICmpULE(Idx, 1415 llvm::ConstantInt::get(Idx->getType(), Size)), 1416 Cont, getTrapBB()); 1417 EmitBlock(Cont); 1418 } 1419 } 1420 } 1421 } 1422 } 1423 1424 // We know that the pointer points to a type of the correct size, unless the 1425 // size is a VLA or Objective-C interface. 1426 llvm::Value *Address = 0; 1427 if (const VariableArrayType *VAT = 1428 getContext().getAsVariableArrayType(E->getType())) { 1429 llvm::Value *VLASize = GetVLASize(VAT); 1430 1431 Idx = Builder.CreateMul(Idx, VLASize); 1432 1433 QualType BaseType = getContext().getBaseElementType(VAT); 1434 1435 CharUnits BaseTypeSize = getContext().getTypeSizeInChars(BaseType); 1436 Idx = Builder.CreateUDiv(Idx, 1437 llvm::ConstantInt::get(Idx->getType(), 1438 BaseTypeSize.getQuantity())); 1439 1440 // The base must be a pointer, which is not an aggregate. Emit it. 1441 llvm::Value *Base = EmitScalarExpr(E->getBase()); 1442 1443 Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx"); 1444 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){ 1445 // Indexing over an interface, as in "NSString *P; P[4];" 1446 llvm::Value *InterfaceSize = 1447 llvm::ConstantInt::get(Idx->getType(), 1448 getContext().getTypeSizeInChars(OIT).getQuantity()); 1449 1450 Idx = Builder.CreateMul(Idx, InterfaceSize); 1451 1452 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext); 1453 1454 // The base must be a pointer, which is not an aggregate. Emit it. 1455 llvm::Value *Base = EmitScalarExpr(E->getBase()); 1456 Address = Builder.CreateGEP(Builder.CreateBitCast(Base, i8PTy), 1457 Idx, "arrayidx"); 1458 Address = Builder.CreateBitCast(Address, Base->getType()); 1459 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) { 1460 // If this is A[i] where A is an array, the frontend will have decayed the 1461 // base to be a ArrayToPointerDecay implicit cast. While correct, it is 1462 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a 1463 // "gep x, i" here. Emit one "gep A, 0, i". 1464 assert(Array->getType()->isArrayType() && 1465 "Array to pointer decay must have array source type!"); 1466 llvm::Value *ArrayPtr = EmitLValue(Array).getAddress(); 1467 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0); 1468 llvm::Value *Args[] = { Zero, Idx }; 1469 1470 Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, Args+2, "arrayidx"); 1471 } else { 1472 // The base must be a pointer, which is not an aggregate. Emit it. 1473 llvm::Value *Base = EmitScalarExpr(E->getBase()); 1474 Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx"); 1475 } 1476 1477 QualType T = E->getBase()->getType()->getPointeeType(); 1478 assert(!T.isNull() && 1479 "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type"); 1480 1481 LValue LV = MakeAddrLValue(Address, T); 1482 LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace()); 1483 1484 if (getContext().getLangOptions().ObjC1 && 1485 getContext().getLangOptions().getGCMode() != LangOptions::NonGC) { 1486 LV.setNonGC(!E->isOBJCGCCandidate(getContext())); 1487 setObjCGCLValueClass(getContext(), E, LV); 1488 } 1489 return LV; 1490 } 1491 1492 static 1493 llvm::Constant *GenerateConstantVector(llvm::LLVMContext &VMContext, 1494 llvm::SmallVector<unsigned, 4> &Elts) { 1495 llvm::SmallVector<llvm::Constant*, 4> CElts; 1496 1497 const llvm::Type *Int32Ty = llvm::Type::getInt32Ty(VMContext); 1498 for (unsigned i = 0, e = Elts.size(); i != e; ++i) 1499 CElts.push_back(llvm::ConstantInt::get(Int32Ty, Elts[i])); 1500 1501 return llvm::ConstantVector::get(&CElts[0], CElts.size()); 1502 } 1503 1504 LValue CodeGenFunction:: 1505 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) { 1506 // Emit the base vector as an l-value. 1507 LValue Base; 1508 1509 // ExtVectorElementExpr's base can either be a vector or pointer to vector. 1510 if (E->isArrow()) { 1511 // If it is a pointer to a vector, emit the address and form an lvalue with 1512 // it. 1513 llvm::Value *Ptr = EmitScalarExpr(E->getBase()); 1514 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>(); 1515 Base = MakeAddrLValue(Ptr, PT->getPointeeType()); 1516 Base.getQuals().removeObjCGCAttr(); 1517 } else if (E->getBase()->isLvalue(getContext()) == Expr::LV_Valid) { 1518 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x), 1519 // emit the base as an lvalue. 1520 assert(E->getBase()->getType()->isVectorType()); 1521 Base = EmitLValue(E->getBase()); 1522 } else { 1523 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such. 1524 assert(E->getBase()->getType()->getAs<VectorType>() && 1525 "Result must be a vector"); 1526 llvm::Value *Vec = EmitScalarExpr(E->getBase()); 1527 1528 // Store the vector to memory (because LValue wants an address). 1529 llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType()); 1530 Builder.CreateStore(Vec, VecMem); 1531 Base = MakeAddrLValue(VecMem, E->getBase()->getType()); 1532 } 1533 1534 // Encode the element access list into a vector of unsigned indices. 1535 llvm::SmallVector<unsigned, 4> Indices; 1536 E->getEncodedElementAccess(Indices); 1537 1538 if (Base.isSimple()) { 1539 llvm::Constant *CV = GenerateConstantVector(VMContext, Indices); 1540 return LValue::MakeExtVectorElt(Base.getAddress(), CV, 1541 Base.getVRQualifiers()); 1542 } 1543 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!"); 1544 1545 llvm::Constant *BaseElts = Base.getExtVectorElts(); 1546 llvm::SmallVector<llvm::Constant *, 4> CElts; 1547 1548 for (unsigned i = 0, e = Indices.size(); i != e; ++i) { 1549 if (isa<llvm::ConstantAggregateZero>(BaseElts)) 1550 CElts.push_back(llvm::ConstantInt::get(Int32Ty, 0)); 1551 else 1552 CElts.push_back(cast<llvm::Constant>(BaseElts->getOperand(Indices[i]))); 1553 } 1554 llvm::Constant *CV = llvm::ConstantVector::get(&CElts[0], CElts.size()); 1555 return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, 1556 Base.getVRQualifiers()); 1557 } 1558 1559 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) { 1560 bool isNonGC = false; 1561 Expr *BaseExpr = E->getBase(); 1562 llvm::Value *BaseValue = NULL; 1563 Qualifiers BaseQuals; 1564 1565 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 1566 if (E->isArrow()) { 1567 BaseValue = EmitScalarExpr(BaseExpr); 1568 const PointerType *PTy = 1569 BaseExpr->getType()->getAs<PointerType>(); 1570 BaseQuals = PTy->getPointeeType().getQualifiers(); 1571 } else if (isa<ObjCPropertyRefExpr>(BaseExpr->IgnoreParens()) || 1572 isa<ObjCImplicitSetterGetterRefExpr>( 1573 BaseExpr->IgnoreParens())) { 1574 RValue RV = EmitObjCPropertyGet(BaseExpr); 1575 BaseValue = RV.getAggregateAddr(); 1576 BaseQuals = BaseExpr->getType().getQualifiers(); 1577 } else { 1578 LValue BaseLV = EmitLValue(BaseExpr); 1579 if (BaseLV.isNonGC()) 1580 isNonGC = true; 1581 // FIXME: this isn't right for bitfields. 1582 BaseValue = BaseLV.getAddress(); 1583 QualType BaseTy = BaseExpr->getType(); 1584 BaseQuals = BaseTy.getQualifiers(); 1585 } 1586 1587 NamedDecl *ND = E->getMemberDecl(); 1588 if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) { 1589 LValue LV = EmitLValueForField(BaseValue, Field, 1590 BaseQuals.getCVRQualifiers()); 1591 LV.setNonGC(isNonGC); 1592 setObjCGCLValueClass(getContext(), E, LV); 1593 return LV; 1594 } 1595 1596 if (VarDecl *VD = dyn_cast<VarDecl>(ND)) 1597 return EmitGlobalVarDeclLValue(*this, E, VD); 1598 1599 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) 1600 return EmitFunctionDeclLValue(*this, E, FD); 1601 1602 assert(false && "Unhandled member declaration!"); 1603 return LValue(); 1604 } 1605 1606 LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value *BaseValue, 1607 const FieldDecl *Field, 1608 unsigned CVRQualifiers) { 1609 const CGRecordLayout &RL = 1610 CGM.getTypes().getCGRecordLayout(Field->getParent()); 1611 const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field); 1612 return LValue::MakeBitfield(BaseValue, Info, 1613 Field->getType().getCVRQualifiers()|CVRQualifiers); 1614 } 1615 1616 /// EmitLValueForAnonRecordField - Given that the field is a member of 1617 /// an anonymous struct or union buried inside a record, and given 1618 /// that the base value is a pointer to the enclosing record, derive 1619 /// an lvalue for the ultimate field. 1620 LValue CodeGenFunction::EmitLValueForAnonRecordField(llvm::Value *BaseValue, 1621 const FieldDecl *Field, 1622 unsigned CVRQualifiers) { 1623 llvm::SmallVector<const FieldDecl *, 8> Path; 1624 Path.push_back(Field); 1625 1626 while (Field->getParent()->isAnonymousStructOrUnion()) { 1627 const ValueDecl *VD = Field->getParent()->getAnonymousStructOrUnionObject(); 1628 if (!isa<FieldDecl>(VD)) break; 1629 Field = cast<FieldDecl>(VD); 1630 Path.push_back(Field); 1631 } 1632 1633 llvm::SmallVectorImpl<const FieldDecl*>::reverse_iterator 1634 I = Path.rbegin(), E = Path.rend(); 1635 while (true) { 1636 LValue LV = EmitLValueForField(BaseValue, *I, CVRQualifiers); 1637 if (++I == E) return LV; 1638 1639 assert(LV.isSimple()); 1640 BaseValue = LV.getAddress(); 1641 CVRQualifiers |= LV.getVRQualifiers(); 1642 } 1643 } 1644 1645 LValue CodeGenFunction::EmitLValueForField(llvm::Value *BaseValue, 1646 const FieldDecl *Field, 1647 unsigned CVRQualifiers) { 1648 if (Field->isBitField()) 1649 return EmitLValueForBitfield(BaseValue, Field, CVRQualifiers); 1650 1651 const CGRecordLayout &RL = 1652 CGM.getTypes().getCGRecordLayout(Field->getParent()); 1653 unsigned idx = RL.getLLVMFieldNo(Field); 1654 llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp"); 1655 1656 // Match union field type. 1657 if (Field->getParent()->isUnion()) { 1658 const llvm::Type *FieldTy = 1659 CGM.getTypes().ConvertTypeForMem(Field->getType()); 1660 const llvm::PointerType *BaseTy = 1661 cast<llvm::PointerType>(BaseValue->getType()); 1662 unsigned AS = BaseTy->getAddressSpace(); 1663 V = Builder.CreateBitCast(V, 1664 llvm::PointerType::get(FieldTy, AS), 1665 "tmp"); 1666 } 1667 if (Field->getType()->isReferenceType()) 1668 V = Builder.CreateLoad(V, "tmp"); 1669 1670 unsigned Alignment = getContext().getDeclAlign(Field).getQuantity(); 1671 LValue LV = MakeAddrLValue(V, Field->getType(), Alignment); 1672 LV.getQuals().addCVRQualifiers(CVRQualifiers); 1673 1674 // __weak attribute on a field is ignored. 1675 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak) 1676 LV.getQuals().removeObjCGCAttr(); 1677 1678 return LV; 1679 } 1680 1681 LValue 1682 CodeGenFunction::EmitLValueForFieldInitialization(llvm::Value *BaseValue, 1683 const FieldDecl *Field, 1684 unsigned CVRQualifiers) { 1685 QualType FieldType = Field->getType(); 1686 1687 if (!FieldType->isReferenceType()) 1688 return EmitLValueForField(BaseValue, Field, CVRQualifiers); 1689 1690 const CGRecordLayout &RL = 1691 CGM.getTypes().getCGRecordLayout(Field->getParent()); 1692 unsigned idx = RL.getLLVMFieldNo(Field); 1693 llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp"); 1694 1695 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs"); 1696 1697 unsigned Alignment = getContext().getDeclAlign(Field).getQuantity(); 1698 return MakeAddrLValue(V, FieldType, Alignment); 1699 } 1700 1701 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){ 1702 llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral"); 1703 const Expr *InitExpr = E->getInitializer(); 1704 LValue Result = MakeAddrLValue(DeclPtr, E->getType()); 1705 1706 EmitAnyExprToMem(InitExpr, DeclPtr, /*Volatile*/ false, /*Init*/ true); 1707 1708 return Result; 1709 } 1710 1711 LValue 1712 CodeGenFunction::EmitConditionalOperatorLValue(const ConditionalOperator *E) { 1713 if (E->isLvalue(getContext()) == Expr::LV_Valid) { 1714 if (int Cond = ConstantFoldsToSimpleInteger(E->getCond())) { 1715 Expr *Live = Cond == 1 ? E->getLHS() : E->getRHS(); 1716 if (Live) 1717 return EmitLValue(Live); 1718 } 1719 1720 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 1721 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 1722 llvm::BasicBlock *ContBlock = createBasicBlock("cond.end"); 1723 1724 if (E->getLHS()) 1725 EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock); 1726 else { 1727 Expr *save = E->getSAVE(); 1728 assert(save && "VisitConditionalOperator - save is null"); 1729 // Intentianlly not doing direct assignment to ConditionalSaveExprs[save] 1730 LValue SaveVal = EmitLValue(save); 1731 ConditionalSaveLValueExprs[save] = SaveVal; 1732 EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock); 1733 } 1734 1735 // Any temporaries created here are conditional. 1736 BeginConditionalBranch(); 1737 EmitBlock(LHSBlock); 1738 LValue LHS = EmitLValue(E->getTrueExpr()); 1739 1740 EndConditionalBranch(); 1741 1742 if (!LHS.isSimple()) 1743 return EmitUnsupportedLValue(E, "conditional operator"); 1744 1745 // FIXME: We shouldn't need an alloca for this. 1746 llvm::Value *Temp = CreateTempAlloca(LHS.getAddress()->getType(),"condtmp"); 1747 Builder.CreateStore(LHS.getAddress(), Temp); 1748 EmitBranch(ContBlock); 1749 1750 // Any temporaries created here are conditional. 1751 BeginConditionalBranch(); 1752 EmitBlock(RHSBlock); 1753 LValue RHS = EmitLValue(E->getRHS()); 1754 EndConditionalBranch(); 1755 if (!RHS.isSimple()) 1756 return EmitUnsupportedLValue(E, "conditional operator"); 1757 1758 Builder.CreateStore(RHS.getAddress(), Temp); 1759 EmitBranch(ContBlock); 1760 1761 EmitBlock(ContBlock); 1762 1763 Temp = Builder.CreateLoad(Temp, "lv"); 1764 return MakeAddrLValue(Temp, E->getType()); 1765 } 1766 1767 // ?: here should be an aggregate. 1768 assert((hasAggregateLLVMType(E->getType()) && 1769 !E->getType()->isAnyComplexType()) && 1770 "Unexpected conditional operator!"); 1771 1772 return EmitAggExprToLValue(E); 1773 } 1774 1775 /// EmitCastLValue - Casts are never lvalues unless that cast is a dynamic_cast. 1776 /// If the cast is a dynamic_cast, we can have the usual lvalue result, 1777 /// otherwise if a cast is needed by the code generator in an lvalue context, 1778 /// then it must mean that we need the address of an aggregate in order to 1779 /// access one of its fields. This can happen for all the reasons that casts 1780 /// are permitted with aggregate result, including noop aggregate casts, and 1781 /// cast from scalar to union. 1782 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) { 1783 switch (E->getCastKind()) { 1784 case CK_ToVoid: 1785 return EmitUnsupportedLValue(E, "unexpected cast lvalue"); 1786 1787 case CK_NoOp: 1788 if (E->getSubExpr()->Classify(getContext()).getKind() 1789 != Expr::Classification::CL_PRValue) { 1790 LValue LV = EmitLValue(E->getSubExpr()); 1791 if (LV.isPropertyRef() || LV.isKVCRef()) { 1792 QualType QT = E->getSubExpr()->getType(); 1793 RValue RV = 1794 LV.isPropertyRef() ? EmitLoadOfPropertyRefLValue(LV, QT) 1795 : EmitLoadOfKVCRefLValue(LV, QT); 1796 assert(!RV.isScalar() && "EmitCastLValue-scalar cast of property ref"); 1797 llvm::Value *V = RV.getAggregateAddr(); 1798 return MakeAddrLValue(V, QT); 1799 } 1800 return LV; 1801 } 1802 // Fall through to synthesize a temporary. 1803 1804 case CK_Unknown: 1805 case CK_BitCast: 1806 case CK_ArrayToPointerDecay: 1807 case CK_FunctionToPointerDecay: 1808 case CK_NullToMemberPointer: 1809 case CK_IntegralToPointer: 1810 case CK_PointerToIntegral: 1811 case CK_VectorSplat: 1812 case CK_IntegralCast: 1813 case CK_IntegralToFloating: 1814 case CK_FloatingToIntegral: 1815 case CK_FloatingCast: 1816 case CK_DerivedToBaseMemberPointer: 1817 case CK_BaseToDerivedMemberPointer: 1818 case CK_MemberPointerToBoolean: 1819 case CK_AnyPointerToBlockPointerCast: { 1820 // These casts only produce lvalues when we're binding a reference to a 1821 // temporary realized from a (converted) pure rvalue. Emit the expression 1822 // as a value, copy it into a temporary, and return an lvalue referring to 1823 // that temporary. 1824 llvm::Value *V = CreateMemTemp(E->getType(), "ref.temp"); 1825 EmitAnyExprToMem(E, V, false, false); 1826 return MakeAddrLValue(V, E->getType()); 1827 } 1828 1829 case CK_Dynamic: { 1830 LValue LV = EmitLValue(E->getSubExpr()); 1831 llvm::Value *V = LV.getAddress(); 1832 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E); 1833 return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType()); 1834 } 1835 1836 case CK_ConstructorConversion: 1837 case CK_UserDefinedConversion: 1838 case CK_AnyPointerToObjCPointerCast: 1839 return EmitLValue(E->getSubExpr()); 1840 1841 case CK_UncheckedDerivedToBase: 1842 case CK_DerivedToBase: { 1843 const RecordType *DerivedClassTy = 1844 E->getSubExpr()->getType()->getAs<RecordType>(); 1845 CXXRecordDecl *DerivedClassDecl = 1846 cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 1847 1848 LValue LV = EmitLValue(E->getSubExpr()); 1849 llvm::Value *This; 1850 if (LV.isPropertyRef() || LV.isKVCRef()) { 1851 QualType QT = E->getSubExpr()->getType(); 1852 RValue RV = 1853 LV.isPropertyRef() ? EmitLoadOfPropertyRefLValue(LV, QT) 1854 : EmitLoadOfKVCRefLValue(LV, QT); 1855 assert (!RV.isScalar() && "EmitCastLValue"); 1856 This = RV.getAggregateAddr(); 1857 } 1858 else 1859 This = LV.getAddress(); 1860 1861 // Perform the derived-to-base conversion 1862 llvm::Value *Base = 1863 GetAddressOfBaseClass(This, DerivedClassDecl, 1864 E->path_begin(), E->path_end(), 1865 /*NullCheckValue=*/false); 1866 1867 return MakeAddrLValue(Base, E->getType()); 1868 } 1869 case CK_ToUnion: 1870 return EmitAggExprToLValue(E); 1871 case CK_BaseToDerived: { 1872 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>(); 1873 CXXRecordDecl *DerivedClassDecl = 1874 cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 1875 1876 LValue LV = EmitLValue(E->getSubExpr()); 1877 1878 // Perform the base-to-derived conversion 1879 llvm::Value *Derived = 1880 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl, 1881 E->path_begin(), E->path_end(), 1882 /*NullCheckValue=*/false); 1883 1884 return MakeAddrLValue(Derived, E->getType()); 1885 } 1886 case CK_LValueBitCast: { 1887 // This must be a reinterpret_cast (or c-style equivalent). 1888 const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E); 1889 1890 LValue LV = EmitLValue(E->getSubExpr()); 1891 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(), 1892 ConvertType(CE->getTypeAsWritten())); 1893 return MakeAddrLValue(V, E->getType()); 1894 } 1895 case CK_ObjCObjectLValueCast: { 1896 LValue LV = EmitLValue(E->getSubExpr()); 1897 QualType ToType = getContext().getLValueReferenceType(E->getType()); 1898 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(), 1899 ConvertType(ToType)); 1900 return MakeAddrLValue(V, E->getType()); 1901 } 1902 } 1903 1904 llvm_unreachable("Unhandled lvalue cast kind?"); 1905 } 1906 1907 LValue CodeGenFunction::EmitNullInitializationLValue( 1908 const CXXScalarValueInitExpr *E) { 1909 QualType Ty = E->getType(); 1910 LValue LV = MakeAddrLValue(CreateMemTemp(Ty), Ty); 1911 EmitNullInitialization(LV.getAddress(), Ty); 1912 return LV; 1913 } 1914 1915 //===--------------------------------------------------------------------===// 1916 // Expression Emission 1917 //===--------------------------------------------------------------------===// 1918 1919 1920 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E, 1921 ReturnValueSlot ReturnValue) { 1922 // Builtins never have block type. 1923 if (E->getCallee()->getType()->isBlockPointerType()) 1924 return EmitBlockCallExpr(E, ReturnValue); 1925 1926 if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E)) 1927 return EmitCXXMemberCallExpr(CE, ReturnValue); 1928 1929 const Decl *TargetDecl = 0; 1930 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E->getCallee())) { 1931 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) { 1932 TargetDecl = DRE->getDecl(); 1933 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(TargetDecl)) 1934 if (unsigned builtinID = FD->getBuiltinID()) 1935 return EmitBuiltinExpr(FD, builtinID, E); 1936 } 1937 } 1938 1939 if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E)) 1940 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl)) 1941 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue); 1942 1943 if (isa<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) { 1944 // C++ [expr.pseudo]p1: 1945 // The result shall only be used as the operand for the function call 1946 // operator (), and the result of such a call has type void. The only 1947 // effect is the evaluation of the postfix-expression before the dot or 1948 // arrow. 1949 EmitScalarExpr(E->getCallee()); 1950 return RValue::get(0); 1951 } 1952 1953 llvm::Value *Callee = EmitScalarExpr(E->getCallee()); 1954 return EmitCall(E->getCallee()->getType(), Callee, ReturnValue, 1955 E->arg_begin(), E->arg_end(), TargetDecl); 1956 } 1957 1958 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) { 1959 // Comma expressions just emit their LHS then their RHS as an l-value. 1960 if (E->getOpcode() == BO_Comma) { 1961 EmitAnyExpr(E->getLHS()); 1962 EnsureInsertPoint(); 1963 return EmitLValue(E->getRHS()); 1964 } 1965 1966 if (E->getOpcode() == BO_PtrMemD || 1967 E->getOpcode() == BO_PtrMemI) 1968 return EmitPointerToDataMemberBinaryExpr(E); 1969 1970 // Can only get l-value for binary operator expressions which are a 1971 // simple assignment of aggregate type. 1972 if (E->getOpcode() != BO_Assign) 1973 return EmitUnsupportedLValue(E, "binary l-value expression"); 1974 1975 if (!hasAggregateLLVMType(E->getType())) { 1976 // Emit the LHS as an l-value. 1977 LValue LV = EmitLValue(E->getLHS()); 1978 // Store the value through the l-value. 1979 EmitStoreThroughLValue(EmitAnyExpr(E->getRHS()), LV, E->getType()); 1980 return LV; 1981 } 1982 1983 return EmitAggExprToLValue(E); 1984 } 1985 1986 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) { 1987 RValue RV = EmitCallExpr(E); 1988 1989 if (!RV.isScalar()) 1990 return MakeAddrLValue(RV.getAggregateAddr(), E->getType()); 1991 1992 assert(E->getCallReturnType()->isReferenceType() && 1993 "Can't have a scalar return unless the return type is a " 1994 "reference type!"); 1995 1996 return MakeAddrLValue(RV.getScalarVal(), E->getType()); 1997 } 1998 1999 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) { 2000 // FIXME: This shouldn't require another copy. 2001 return EmitAggExprToLValue(E); 2002 } 2003 2004 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) { 2005 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor() 2006 && "binding l-value to type which needs a temporary"); 2007 AggValueSlot Slot = CreateAggTemp(E->getType(), "tmp"); 2008 EmitCXXConstructExpr(E, Slot); 2009 return MakeAddrLValue(Slot.getAddr(), E->getType()); 2010 } 2011 2012 LValue 2013 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) { 2014 return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType()); 2015 } 2016 2017 LValue 2018 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) { 2019 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue"); 2020 Slot.setLifetimeExternallyManaged(); 2021 EmitAggExpr(E->getSubExpr(), Slot); 2022 EmitCXXTemporary(E->getTemporary(), Slot.getAddr()); 2023 return MakeAddrLValue(Slot.getAddr(), E->getType()); 2024 } 2025 2026 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) { 2027 RValue RV = EmitObjCMessageExpr(E); 2028 2029 if (!RV.isScalar()) 2030 return MakeAddrLValue(RV.getAggregateAddr(), E->getType()); 2031 2032 assert(E->getMethodDecl()->getResultType()->isReferenceType() && 2033 "Can't have a scalar return unless the return type is a " 2034 "reference type!"); 2035 2036 return MakeAddrLValue(RV.getScalarVal(), E->getType()); 2037 } 2038 2039 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) { 2040 llvm::Value *V = 2041 CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true); 2042 return MakeAddrLValue(V, E->getType()); 2043 } 2044 2045 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface, 2046 const ObjCIvarDecl *Ivar) { 2047 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar); 2048 } 2049 2050 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy, 2051 llvm::Value *BaseValue, 2052 const ObjCIvarDecl *Ivar, 2053 unsigned CVRQualifiers) { 2054 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue, 2055 Ivar, CVRQualifiers); 2056 } 2057 2058 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) { 2059 // FIXME: A lot of the code below could be shared with EmitMemberExpr. 2060 llvm::Value *BaseValue = 0; 2061 const Expr *BaseExpr = E->getBase(); 2062 Qualifiers BaseQuals; 2063 QualType ObjectTy; 2064 if (E->isArrow()) { 2065 BaseValue = EmitScalarExpr(BaseExpr); 2066 ObjectTy = BaseExpr->getType()->getPointeeType(); 2067 BaseQuals = ObjectTy.getQualifiers(); 2068 } else { 2069 LValue BaseLV = EmitLValue(BaseExpr); 2070 // FIXME: this isn't right for bitfields. 2071 BaseValue = BaseLV.getAddress(); 2072 ObjectTy = BaseExpr->getType(); 2073 BaseQuals = ObjectTy.getQualifiers(); 2074 } 2075 2076 LValue LV = 2077 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(), 2078 BaseQuals.getCVRQualifiers()); 2079 setObjCGCLValueClass(getContext(), E, LV); 2080 return LV; 2081 } 2082 2083 LValue 2084 CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) { 2085 // This is a special l-value that just issues sends when we load or store 2086 // through it. 2087 return LValue::MakePropertyRef(E, E->getType().getCVRQualifiers()); 2088 } 2089 2090 LValue CodeGenFunction::EmitObjCKVCRefLValue( 2091 const ObjCImplicitSetterGetterRefExpr *E) { 2092 // This is a special l-value that just issues sends when we load or store 2093 // through it. 2094 return LValue::MakeKVCRef(E, E->getType().getCVRQualifiers()); 2095 } 2096 2097 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) { 2098 // Can only get l-value for message expression returning aggregate type 2099 RValue RV = EmitAnyExprToTemp(E); 2100 return MakeAddrLValue(RV.getAggregateAddr(), E->getType()); 2101 } 2102 2103 RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee, 2104 ReturnValueSlot ReturnValue, 2105 CallExpr::const_arg_iterator ArgBeg, 2106 CallExpr::const_arg_iterator ArgEnd, 2107 const Decl *TargetDecl) { 2108 // Get the actual function type. The callee type will always be a pointer to 2109 // function type or a block pointer type. 2110 assert(CalleeType->isFunctionPointerType() && 2111 "Call must have function pointer type!"); 2112 2113 CalleeType = getContext().getCanonicalType(CalleeType); 2114 2115 const FunctionType *FnType 2116 = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType()); 2117 QualType ResultType = FnType->getResultType(); 2118 2119 CallArgList Args; 2120 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd); 2121 2122 return EmitCall(CGM.getTypes().getFunctionInfo(Args, FnType), 2123 Callee, ReturnValue, Args, TargetDecl); 2124 } 2125 2126 LValue CodeGenFunction:: 2127 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) { 2128 llvm::Value *BaseV; 2129 if (E->getOpcode() == BO_PtrMemI) 2130 BaseV = EmitScalarExpr(E->getLHS()); 2131 else 2132 BaseV = EmitLValue(E->getLHS()).getAddress(); 2133 2134 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS()); 2135 2136 const MemberPointerType *MPT 2137 = E->getRHS()->getType()->getAs<MemberPointerType>(); 2138 2139 llvm::Value *AddV = 2140 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, BaseV, OffsetV, MPT); 2141 2142 return MakeAddrLValue(AddV, MPT->getPointeeType()); 2143 } 2144 2145