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