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