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