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