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