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 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) { 1321 // The index must always be an integer, which is not an aggregate. Emit it. 1322 llvm::Value *Idx = EmitScalarExpr(E->getIdx()); 1323 QualType IdxTy = E->getIdx()->getType(); 1324 bool IdxSigned = IdxTy->isSignedIntegerType(); 1325 1326 // If the base is a vector type, then we are forming a vector element lvalue 1327 // with this subscript. 1328 if (E->getBase()->getType()->isVectorType()) { 1329 // Emit the vector as an lvalue to get its address. 1330 LValue LHS = EmitLValue(E->getBase()); 1331 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!"); 1332 Idx = Builder.CreateIntCast(Idx, 1333 llvm::Type::getInt32Ty(VMContext), IdxSigned, "vidx"); 1334 return LValue::MakeVectorElt(LHS.getAddress(), Idx, 1335 E->getBase()->getType().getCVRQualifiers()); 1336 } 1337 1338 // Extend or truncate the index type to 32 or 64-bits. 1339 if (!Idx->getType()->isIntegerTy(LLVMPointerWidth)) 1340 Idx = Builder.CreateIntCast(Idx, 1341 llvm::IntegerType::get(VMContext, LLVMPointerWidth), 1342 IdxSigned, "idxprom"); 1343 1344 // FIXME: As llvm implements the object size checking, this can come out. 1345 if (CatchUndefined) { 1346 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E->getBase())){ 1347 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) { 1348 if (ICE->getCastKind() == CastExpr::CK_ArrayToPointerDecay) { 1349 if (const ConstantArrayType *CAT 1350 = getContext().getAsConstantArrayType(DRE->getType())) { 1351 llvm::APInt Size = CAT->getSize(); 1352 llvm::BasicBlock *Cont = createBasicBlock("cont"); 1353 Builder.CreateCondBr(Builder.CreateICmpULE(Idx, 1354 llvm::ConstantInt::get(Idx->getType(), Size)), 1355 Cont, getTrapBB()); 1356 EmitBlock(Cont); 1357 } 1358 } 1359 } 1360 } 1361 } 1362 1363 // The base must be a pointer, which is not an aggregate. Emit it. 1364 llvm::Value *Base = EmitScalarExpr(E->getBase()); 1365 1366 // We know that the pointer points to a type of the correct size, unless the 1367 // size is a VLA or Objective-C interface. 1368 llvm::Value *Address = 0; 1369 if (const VariableArrayType *VAT = 1370 getContext().getAsVariableArrayType(E->getType())) { 1371 llvm::Value *VLASize = GetVLASize(VAT); 1372 1373 Idx = Builder.CreateMul(Idx, VLASize); 1374 1375 QualType BaseType = getContext().getBaseElementType(VAT); 1376 1377 CharUnits BaseTypeSize = getContext().getTypeSizeInChars(BaseType); 1378 Idx = Builder.CreateUDiv(Idx, 1379 llvm::ConstantInt::get(Idx->getType(), 1380 BaseTypeSize.getQuantity())); 1381 Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx"); 1382 } else if (const ObjCObjectType *OIT = 1383 E->getType()->getAs<ObjCObjectType>()) { 1384 llvm::Value *InterfaceSize = 1385 llvm::ConstantInt::get(Idx->getType(), 1386 getContext().getTypeSizeInChars(OIT).getQuantity()); 1387 1388 Idx = Builder.CreateMul(Idx, InterfaceSize); 1389 1390 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext); 1391 Address = Builder.CreateGEP(Builder.CreateBitCast(Base, i8PTy), 1392 Idx, "arrayidx"); 1393 Address = Builder.CreateBitCast(Address, Base->getType()); 1394 } else { 1395 Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx"); 1396 } 1397 1398 QualType T = E->getBase()->getType()->getPointeeType(); 1399 assert(!T.isNull() && 1400 "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type"); 1401 1402 Qualifiers Quals = MakeQualifiers(T); 1403 Quals.setAddressSpace(E->getBase()->getType().getAddressSpace()); 1404 1405 LValue LV = LValue::MakeAddr(Address, Quals); 1406 if (getContext().getLangOptions().ObjC1 && 1407 getContext().getLangOptions().getGCMode() != LangOptions::NonGC) { 1408 LValue::SetObjCNonGC(LV, !E->isOBJCGCCandidate(getContext())); 1409 setObjCGCLValueClass(getContext(), E, LV); 1410 } 1411 return LV; 1412 } 1413 1414 static 1415 llvm::Constant *GenerateConstantVector(llvm::LLVMContext &VMContext, 1416 llvm::SmallVector<unsigned, 4> &Elts) { 1417 llvm::SmallVector<llvm::Constant*, 4> CElts; 1418 1419 for (unsigned i = 0, e = Elts.size(); i != e; ++i) 1420 CElts.push_back(llvm::ConstantInt::get( 1421 llvm::Type::getInt32Ty(VMContext), Elts[i])); 1422 1423 return llvm::ConstantVector::get(&CElts[0], CElts.size()); 1424 } 1425 1426 LValue CodeGenFunction:: 1427 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) { 1428 const llvm::Type *Int32Ty = llvm::Type::getInt32Ty(VMContext); 1429 1430 // Emit the base vector as an l-value. 1431 LValue Base; 1432 1433 // ExtVectorElementExpr's base can either be a vector or pointer to vector. 1434 if (E->isArrow()) { 1435 // If it is a pointer to a vector, emit the address and form an lvalue with 1436 // it. 1437 llvm::Value *Ptr = EmitScalarExpr(E->getBase()); 1438 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>(); 1439 Qualifiers Quals = MakeQualifiers(PT->getPointeeType()); 1440 Quals.removeObjCGCAttr(); 1441 Base = LValue::MakeAddr(Ptr, Quals); 1442 } else if (E->getBase()->isLvalue(getContext()) == Expr::LV_Valid) { 1443 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x), 1444 // emit the base as an lvalue. 1445 assert(E->getBase()->getType()->isVectorType()); 1446 Base = EmitLValue(E->getBase()); 1447 } else { 1448 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such. 1449 assert(E->getBase()->getType()->getAs<VectorType>() && 1450 "Result must be a vector"); 1451 llvm::Value *Vec = EmitScalarExpr(E->getBase()); 1452 1453 // Store the vector to memory (because LValue wants an address). 1454 llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType()); 1455 Builder.CreateStore(Vec, VecMem); 1456 Base = LValue::MakeAddr(VecMem, Qualifiers()); 1457 } 1458 1459 // Encode the element access list into a vector of unsigned indices. 1460 llvm::SmallVector<unsigned, 4> Indices; 1461 E->getEncodedElementAccess(Indices); 1462 1463 if (Base.isSimple()) { 1464 llvm::Constant *CV = GenerateConstantVector(VMContext, Indices); 1465 return LValue::MakeExtVectorElt(Base.getAddress(), CV, 1466 Base.getVRQualifiers()); 1467 } 1468 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!"); 1469 1470 llvm::Constant *BaseElts = Base.getExtVectorElts(); 1471 llvm::SmallVector<llvm::Constant *, 4> CElts; 1472 1473 for (unsigned i = 0, e = Indices.size(); i != e; ++i) { 1474 if (isa<llvm::ConstantAggregateZero>(BaseElts)) 1475 CElts.push_back(llvm::ConstantInt::get(Int32Ty, 0)); 1476 else 1477 CElts.push_back(cast<llvm::Constant>(BaseElts->getOperand(Indices[i]))); 1478 } 1479 llvm::Constant *CV = llvm::ConstantVector::get(&CElts[0], CElts.size()); 1480 return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, 1481 Base.getVRQualifiers()); 1482 } 1483 1484 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) { 1485 bool isNonGC = false; 1486 Expr *BaseExpr = E->getBase(); 1487 llvm::Value *BaseValue = NULL; 1488 Qualifiers BaseQuals; 1489 1490 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 1491 if (E->isArrow()) { 1492 BaseValue = EmitScalarExpr(BaseExpr); 1493 const PointerType *PTy = 1494 BaseExpr->getType()->getAs<PointerType>(); 1495 BaseQuals = PTy->getPointeeType().getQualifiers(); 1496 } else if (isa<ObjCPropertyRefExpr>(BaseExpr->IgnoreParens()) || 1497 isa<ObjCImplicitSetterGetterRefExpr>( 1498 BaseExpr->IgnoreParens())) { 1499 RValue RV = EmitObjCPropertyGet(BaseExpr); 1500 BaseValue = RV.getAggregateAddr(); 1501 BaseQuals = BaseExpr->getType().getQualifiers(); 1502 } else { 1503 LValue BaseLV = EmitLValue(BaseExpr); 1504 if (BaseLV.isNonGC()) 1505 isNonGC = true; 1506 // FIXME: this isn't right for bitfields. 1507 BaseValue = BaseLV.getAddress(); 1508 QualType BaseTy = BaseExpr->getType(); 1509 BaseQuals = BaseTy.getQualifiers(); 1510 } 1511 1512 NamedDecl *ND = E->getMemberDecl(); 1513 if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) { 1514 LValue LV = EmitLValueForField(BaseValue, Field, 1515 BaseQuals.getCVRQualifiers()); 1516 LValue::SetObjCNonGC(LV, isNonGC); 1517 setObjCGCLValueClass(getContext(), E, LV); 1518 return LV; 1519 } 1520 1521 if (VarDecl *VD = dyn_cast<VarDecl>(ND)) 1522 return EmitGlobalVarDeclLValue(*this, E, VD); 1523 1524 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) 1525 return EmitFunctionDeclLValue(*this, E, FD); 1526 1527 assert(false && "Unhandled member declaration!"); 1528 return LValue(); 1529 } 1530 1531 LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value* BaseValue, 1532 const FieldDecl* Field, 1533 unsigned CVRQualifiers) { 1534 const CGRecordLayout &RL = 1535 CGM.getTypes().getCGRecordLayout(Field->getParent()); 1536 const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field); 1537 return LValue::MakeBitfield(BaseValue, Info, 1538 Field->getType().getCVRQualifiers()|CVRQualifiers); 1539 } 1540 1541 /// EmitLValueForAnonRecordField - Given that the field is a member of 1542 /// an anonymous struct or union buried inside a record, and given 1543 /// that the base value is a pointer to the enclosing record, derive 1544 /// an lvalue for the ultimate field. 1545 LValue CodeGenFunction::EmitLValueForAnonRecordField(llvm::Value *BaseValue, 1546 const FieldDecl *Field, 1547 unsigned CVRQualifiers) { 1548 llvm::SmallVector<const FieldDecl *, 8> Path; 1549 Path.push_back(Field); 1550 1551 while (Field->getParent()->isAnonymousStructOrUnion()) { 1552 const ValueDecl *VD = Field->getParent()->getAnonymousStructOrUnionObject(); 1553 if (!isa<FieldDecl>(VD)) break; 1554 Field = cast<FieldDecl>(VD); 1555 Path.push_back(Field); 1556 } 1557 1558 llvm::SmallVectorImpl<const FieldDecl*>::reverse_iterator 1559 I = Path.rbegin(), E = Path.rend(); 1560 while (true) { 1561 LValue LV = EmitLValueForField(BaseValue, *I, CVRQualifiers); 1562 if (++I == E) return LV; 1563 1564 assert(LV.isSimple()); 1565 BaseValue = LV.getAddress(); 1566 CVRQualifiers |= LV.getVRQualifiers(); 1567 } 1568 } 1569 1570 LValue CodeGenFunction::EmitLValueForField(llvm::Value* BaseValue, 1571 const FieldDecl* Field, 1572 unsigned CVRQualifiers) { 1573 if (Field->isBitField()) 1574 return EmitLValueForBitfield(BaseValue, Field, CVRQualifiers); 1575 1576 const CGRecordLayout &RL = 1577 CGM.getTypes().getCGRecordLayout(Field->getParent()); 1578 unsigned idx = RL.getLLVMFieldNo(Field); 1579 llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp"); 1580 1581 // Match union field type. 1582 if (Field->getParent()->isUnion()) { 1583 const llvm::Type *FieldTy = 1584 CGM.getTypes().ConvertTypeForMem(Field->getType()); 1585 const llvm::PointerType * BaseTy = 1586 cast<llvm::PointerType>(BaseValue->getType()); 1587 unsigned AS = BaseTy->getAddressSpace(); 1588 V = Builder.CreateBitCast(V, 1589 llvm::PointerType::get(FieldTy, AS), 1590 "tmp"); 1591 } 1592 if (Field->getType()->isReferenceType()) 1593 V = Builder.CreateLoad(V, "tmp"); 1594 1595 Qualifiers Quals = MakeQualifiers(Field->getType()); 1596 Quals.addCVRQualifiers(CVRQualifiers); 1597 // __weak attribute on a field is ignored. 1598 if (Quals.getObjCGCAttr() == Qualifiers::Weak) 1599 Quals.removeObjCGCAttr(); 1600 1601 return LValue::MakeAddr(V, Quals); 1602 } 1603 1604 LValue 1605 CodeGenFunction::EmitLValueForFieldInitialization(llvm::Value* BaseValue, 1606 const FieldDecl* Field, 1607 unsigned CVRQualifiers) { 1608 QualType FieldType = Field->getType(); 1609 1610 if (!FieldType->isReferenceType()) 1611 return EmitLValueForField(BaseValue, Field, CVRQualifiers); 1612 1613 const CGRecordLayout &RL = 1614 CGM.getTypes().getCGRecordLayout(Field->getParent()); 1615 unsigned idx = RL.getLLVMFieldNo(Field); 1616 llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp"); 1617 1618 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs"); 1619 1620 return LValue::MakeAddr(V, MakeQualifiers(FieldType)); 1621 } 1622 1623 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr* E){ 1624 llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral"); 1625 const Expr* InitExpr = E->getInitializer(); 1626 LValue Result = LValue::MakeAddr(DeclPtr, MakeQualifiers(E->getType())); 1627 1628 EmitAnyExprToMem(InitExpr, DeclPtr, /*Volatile*/ false); 1629 1630 return Result; 1631 } 1632 1633 LValue 1634 CodeGenFunction::EmitConditionalOperatorLValue(const ConditionalOperator* E) { 1635 if (E->isLvalue(getContext()) == Expr::LV_Valid) { 1636 if (int Cond = ConstantFoldsToSimpleInteger(E->getCond())) { 1637 Expr *Live = Cond == 1 ? E->getLHS() : E->getRHS(); 1638 if (Live) 1639 return EmitLValue(Live); 1640 } 1641 1642 if (!E->getLHS()) 1643 return EmitUnsupportedLValue(E, "conditional operator with missing LHS"); 1644 1645 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 1646 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 1647 llvm::BasicBlock *ContBlock = createBasicBlock("cond.end"); 1648 1649 EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock); 1650 1651 // Any temporaries created here are conditional. 1652 BeginConditionalBranch(); 1653 EmitBlock(LHSBlock); 1654 LValue LHS = EmitLValue(E->getLHS()); 1655 EndConditionalBranch(); 1656 1657 if (!LHS.isSimple()) 1658 return EmitUnsupportedLValue(E, "conditional operator"); 1659 1660 // FIXME: We shouldn't need an alloca for this. 1661 llvm::Value *Temp = CreateTempAlloca(LHS.getAddress()->getType(),"condtmp"); 1662 Builder.CreateStore(LHS.getAddress(), Temp); 1663 EmitBranch(ContBlock); 1664 1665 // Any temporaries created here are conditional. 1666 BeginConditionalBranch(); 1667 EmitBlock(RHSBlock); 1668 LValue RHS = EmitLValue(E->getRHS()); 1669 EndConditionalBranch(); 1670 if (!RHS.isSimple()) 1671 return EmitUnsupportedLValue(E, "conditional operator"); 1672 1673 Builder.CreateStore(RHS.getAddress(), Temp); 1674 EmitBranch(ContBlock); 1675 1676 EmitBlock(ContBlock); 1677 1678 Temp = Builder.CreateLoad(Temp, "lv"); 1679 return LValue::MakeAddr(Temp, MakeQualifiers(E->getType())); 1680 } 1681 1682 // ?: here should be an aggregate. 1683 assert((hasAggregateLLVMType(E->getType()) && 1684 !E->getType()->isAnyComplexType()) && 1685 "Unexpected conditional operator!"); 1686 1687 return EmitAggExprToLValue(E); 1688 } 1689 1690 /// EmitCastLValue - Casts are never lvalues unless that cast is a dynamic_cast. 1691 /// If the cast is a dynamic_cast, we can have the usual lvalue result, 1692 /// otherwise if a cast is needed by the code generator in an lvalue context, 1693 /// then it must mean that we need the address of an aggregate in order to 1694 /// access one of its fields. This can happen for all the reasons that casts 1695 /// are permitted with aggregate result, including noop aggregate casts, and 1696 /// cast from scalar to union. 1697 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) { 1698 switch (E->getCastKind()) { 1699 default: 1700 return EmitUnsupportedLValue(E, "unexpected cast lvalue"); 1701 1702 case CastExpr::CK_Dynamic: { 1703 LValue LV = EmitLValue(E->getSubExpr()); 1704 llvm::Value *V = LV.getAddress(); 1705 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E); 1706 return LValue::MakeAddr(EmitDynamicCast(V, DCE), 1707 MakeQualifiers(E->getType())); 1708 } 1709 1710 case CastExpr::CK_NoOp: { 1711 LValue LV = EmitLValue(E->getSubExpr()); 1712 if (LV.isPropertyRef()) { 1713 QualType QT = E->getSubExpr()->getType(); 1714 RValue RV = EmitLoadOfPropertyRefLValue(LV, QT); 1715 assert(!RV.isScalar() && "EmitCastLValue - scalar cast of property ref"); 1716 llvm::Value *V = RV.getAggregateAddr(); 1717 return LValue::MakeAddr(V, MakeQualifiers(QT)); 1718 } 1719 return LV; 1720 } 1721 case CastExpr::CK_ConstructorConversion: 1722 case CastExpr::CK_UserDefinedConversion: 1723 case CastExpr::CK_AnyPointerToObjCPointerCast: 1724 return EmitLValue(E->getSubExpr()); 1725 1726 case CastExpr::CK_UncheckedDerivedToBase: 1727 case CastExpr::CK_DerivedToBase: { 1728 const RecordType *DerivedClassTy = 1729 E->getSubExpr()->getType()->getAs<RecordType>(); 1730 CXXRecordDecl *DerivedClassDecl = 1731 cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 1732 1733 LValue LV = EmitLValue(E->getSubExpr()); 1734 llvm::Value *This; 1735 if (LV.isPropertyRef()) { 1736 RValue RV = EmitLoadOfPropertyRefLValue(LV, E->getSubExpr()->getType()); 1737 assert (!RV.isScalar() && "EmitCastLValue"); 1738 This = RV.getAggregateAddr(); 1739 } 1740 else 1741 This = LV.getAddress(); 1742 1743 // Perform the derived-to-base conversion 1744 llvm::Value *Base = 1745 GetAddressOfBaseClass(This, DerivedClassDecl, 1746 E->getBasePath(), /*NullCheckValue=*/false); 1747 1748 return LValue::MakeAddr(Base, MakeQualifiers(E->getType())); 1749 } 1750 case CastExpr::CK_ToUnion: 1751 return EmitAggExprToLValue(E); 1752 case CastExpr::CK_BaseToDerived: { 1753 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>(); 1754 CXXRecordDecl *DerivedClassDecl = 1755 cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 1756 1757 LValue LV = EmitLValue(E->getSubExpr()); 1758 1759 // Perform the base-to-derived conversion 1760 llvm::Value *Derived = 1761 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl, 1762 E->getBasePath(),/*NullCheckValue=*/false); 1763 1764 return LValue::MakeAddr(Derived, MakeQualifiers(E->getType())); 1765 } 1766 case CastExpr::CK_BitCast: { 1767 // This must be a reinterpret_cast (or c-style equivalent). 1768 const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E); 1769 1770 LValue LV = EmitLValue(E->getSubExpr()); 1771 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(), 1772 ConvertType(CE->getTypeAsWritten())); 1773 return LValue::MakeAddr(V, MakeQualifiers(E->getType())); 1774 } 1775 } 1776 } 1777 1778 LValue CodeGenFunction::EmitNullInitializationLValue( 1779 const CXXZeroInitValueExpr *E) { 1780 QualType Ty = E->getType(); 1781 LValue LV = LValue::MakeAddr(CreateMemTemp(Ty), MakeQualifiers(Ty)); 1782 EmitNullInitialization(LV.getAddress(), Ty); 1783 return LV; 1784 } 1785 1786 //===--------------------------------------------------------------------===// 1787 // Expression Emission 1788 //===--------------------------------------------------------------------===// 1789 1790 1791 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E, 1792 ReturnValueSlot ReturnValue) { 1793 // Builtins never have block type. 1794 if (E->getCallee()->getType()->isBlockPointerType()) 1795 return EmitBlockCallExpr(E, ReturnValue); 1796 1797 if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E)) 1798 return EmitCXXMemberCallExpr(CE, ReturnValue); 1799 1800 const Decl *TargetDecl = 0; 1801 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E->getCallee())) { 1802 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) { 1803 TargetDecl = DRE->getDecl(); 1804 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(TargetDecl)) 1805 if (unsigned builtinID = FD->getBuiltinID()) 1806 return EmitBuiltinExpr(FD, builtinID, E); 1807 } 1808 } 1809 1810 if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E)) 1811 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl)) 1812 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue); 1813 1814 if (isa<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) { 1815 // C++ [expr.pseudo]p1: 1816 // The result shall only be used as the operand for the function call 1817 // operator (), and the result of such a call has type void. The only 1818 // effect is the evaluation of the postfix-expression before the dot or 1819 // arrow. 1820 EmitScalarExpr(E->getCallee()); 1821 return RValue::get(0); 1822 } 1823 1824 llvm::Value *Callee = EmitScalarExpr(E->getCallee()); 1825 return EmitCall(E->getCallee()->getType(), Callee, ReturnValue, 1826 E->arg_begin(), E->arg_end(), TargetDecl); 1827 } 1828 1829 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) { 1830 // Comma expressions just emit their LHS then their RHS as an l-value. 1831 if (E->getOpcode() == BinaryOperator::Comma) { 1832 EmitAnyExpr(E->getLHS()); 1833 EnsureInsertPoint(); 1834 return EmitLValue(E->getRHS()); 1835 } 1836 1837 if (E->getOpcode() == BinaryOperator::PtrMemD || 1838 E->getOpcode() == BinaryOperator::PtrMemI) 1839 return EmitPointerToDataMemberBinaryExpr(E); 1840 1841 // Can only get l-value for binary operator expressions which are a 1842 // simple assignment of aggregate type. 1843 if (E->getOpcode() != BinaryOperator::Assign) 1844 return EmitUnsupportedLValue(E, "binary l-value expression"); 1845 1846 if (!hasAggregateLLVMType(E->getType())) { 1847 // Emit the LHS as an l-value. 1848 LValue LV = EmitLValue(E->getLHS()); 1849 1850 llvm::Value *RHS = EmitScalarExpr(E->getRHS()); 1851 EmitStoreOfScalar(RHS, LV.getAddress(), LV.isVolatileQualified(), 1852 E->getType()); 1853 return LV; 1854 } 1855 1856 return EmitAggExprToLValue(E); 1857 } 1858 1859 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) { 1860 RValue RV = EmitCallExpr(E); 1861 1862 if (!RV.isScalar()) 1863 return LValue::MakeAddr(RV.getAggregateAddr(),MakeQualifiers(E->getType())); 1864 1865 assert(E->getCallReturnType()->isReferenceType() && 1866 "Can't have a scalar return unless the return type is a " 1867 "reference type!"); 1868 1869 return LValue::MakeAddr(RV.getScalarVal(), MakeQualifiers(E->getType())); 1870 } 1871 1872 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) { 1873 // FIXME: This shouldn't require another copy. 1874 return EmitAggExprToLValue(E); 1875 } 1876 1877 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) { 1878 llvm::Value *Temp = CreateMemTemp(E->getType(), "tmp"); 1879 EmitCXXConstructExpr(Temp, E); 1880 return LValue::MakeAddr(Temp, MakeQualifiers(E->getType())); 1881 } 1882 1883 LValue 1884 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) { 1885 llvm::Value *Temp = EmitCXXTypeidExpr(E); 1886 return LValue::MakeAddr(Temp, MakeQualifiers(E->getType())); 1887 } 1888 1889 LValue 1890 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) { 1891 LValue LV = EmitLValue(E->getSubExpr()); 1892 PushCXXTemporary(E->getTemporary(), LV.getAddress()); 1893 return LV; 1894 } 1895 1896 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) { 1897 RValue RV = EmitObjCMessageExpr(E); 1898 1899 if (!RV.isScalar()) 1900 return LValue::MakeAddr(RV.getAggregateAddr(), 1901 MakeQualifiers(E->getType())); 1902 1903 assert(E->getMethodDecl()->getResultType()->isReferenceType() && 1904 "Can't have a scalar return unless the return type is a " 1905 "reference type!"); 1906 1907 return LValue::MakeAddr(RV.getScalarVal(), MakeQualifiers(E->getType())); 1908 } 1909 1910 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) { 1911 llvm::Value *V = 1912 CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true); 1913 return LValue::MakeAddr(V, MakeQualifiers(E->getType())); 1914 } 1915 1916 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface, 1917 const ObjCIvarDecl *Ivar) { 1918 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar); 1919 } 1920 1921 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy, 1922 llvm::Value *BaseValue, 1923 const ObjCIvarDecl *Ivar, 1924 unsigned CVRQualifiers) { 1925 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue, 1926 Ivar, CVRQualifiers); 1927 } 1928 1929 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) { 1930 // FIXME: A lot of the code below could be shared with EmitMemberExpr. 1931 llvm::Value *BaseValue = 0; 1932 const Expr *BaseExpr = E->getBase(); 1933 Qualifiers BaseQuals; 1934 QualType ObjectTy; 1935 if (E->isArrow()) { 1936 BaseValue = EmitScalarExpr(BaseExpr); 1937 ObjectTy = BaseExpr->getType()->getPointeeType(); 1938 BaseQuals = ObjectTy.getQualifiers(); 1939 } else { 1940 LValue BaseLV = EmitLValue(BaseExpr); 1941 // FIXME: this isn't right for bitfields. 1942 BaseValue = BaseLV.getAddress(); 1943 ObjectTy = BaseExpr->getType(); 1944 BaseQuals = ObjectTy.getQualifiers(); 1945 } 1946 1947 LValue LV = 1948 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(), 1949 BaseQuals.getCVRQualifiers()); 1950 setObjCGCLValueClass(getContext(), E, LV); 1951 return LV; 1952 } 1953 1954 LValue 1955 CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) { 1956 // This is a special l-value that just issues sends when we load or store 1957 // through it. 1958 return LValue::MakePropertyRef(E, E->getType().getCVRQualifiers()); 1959 } 1960 1961 LValue CodeGenFunction::EmitObjCKVCRefLValue( 1962 const ObjCImplicitSetterGetterRefExpr *E) { 1963 // This is a special l-value that just issues sends when we load or store 1964 // through it. 1965 return LValue::MakeKVCRef(E, E->getType().getCVRQualifiers()); 1966 } 1967 1968 LValue CodeGenFunction::EmitObjCSuperExprLValue(const ObjCSuperExpr *E) { 1969 return EmitUnsupportedLValue(E, "use of super"); 1970 } 1971 1972 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) { 1973 // Can only get l-value for message expression returning aggregate type 1974 RValue RV = EmitAnyExprToTemp(E); 1975 return LValue::MakeAddr(RV.getAggregateAddr(), MakeQualifiers(E->getType())); 1976 } 1977 1978 RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee, 1979 ReturnValueSlot ReturnValue, 1980 CallExpr::const_arg_iterator ArgBeg, 1981 CallExpr::const_arg_iterator ArgEnd, 1982 const Decl *TargetDecl) { 1983 // Get the actual function type. The callee type will always be a pointer to 1984 // function type or a block pointer type. 1985 assert(CalleeType->isFunctionPointerType() && 1986 "Call must have function pointer type!"); 1987 1988 CalleeType = getContext().getCanonicalType(CalleeType); 1989 1990 const FunctionType *FnType 1991 = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType()); 1992 QualType ResultType = FnType->getResultType(); 1993 1994 CallArgList Args; 1995 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd); 1996 1997 return EmitCall(CGM.getTypes().getFunctionInfo(Args, FnType), 1998 Callee, ReturnValue, Args, TargetDecl); 1999 } 2000 2001 LValue CodeGenFunction:: 2002 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) { 2003 llvm::Value *BaseV; 2004 if (E->getOpcode() == BinaryOperator::PtrMemI) 2005 BaseV = EmitScalarExpr(E->getLHS()); 2006 else 2007 BaseV = EmitLValue(E->getLHS()).getAddress(); 2008 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(getLLVMContext()); 2009 BaseV = Builder.CreateBitCast(BaseV, i8Ty); 2010 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS()); 2011 llvm::Value *AddV = Builder.CreateInBoundsGEP(BaseV, OffsetV, "add.ptr"); 2012 2013 QualType Ty = E->getRHS()->getType(); 2014 Ty = Ty->getAs<MemberPointerType>()->getPointeeType(); 2015 2016 const llvm::Type *PType = ConvertType(getContext().getPointerType(Ty)); 2017 AddV = Builder.CreateBitCast(AddV, PType); 2018 return LValue::MakeAddr(AddV, MakeQualifiers(Ty)); 2019 } 2020 2021