CGExpr.cpp revision dc47bdc43c62bf2ff01bc71c811a66cb5376d318
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 "TargetInfo.h" 22#include "clang/AST/ASTContext.h" 23#include "clang/AST/DeclObjC.h" 24#include "clang/Basic/ConvertUTF.h" 25#include "clang/Frontend/CodeGenOptions.h" 26#include "llvm/Intrinsics.h" 27#include "llvm/LLVMContext.h" 28#include "llvm/MDBuilder.h" 29#include "llvm/DataLayout.h" 30using namespace clang; 31using namespace CodeGen; 32 33//===--------------------------------------------------------------------===// 34// Miscellaneous Helper Methods 35//===--------------------------------------------------------------------===// 36 37llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) { 38 unsigned addressSpace = 39 cast<llvm::PointerType>(value->getType())->getAddressSpace(); 40 41 llvm::PointerType *destType = Int8PtrTy; 42 if (addressSpace) 43 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace); 44 45 if (value->getType() == destType) return value; 46 return Builder.CreateBitCast(value, destType); 47} 48 49/// CreateTempAlloca - This creates a alloca and inserts it into the entry 50/// block. 51llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, 52 const Twine &Name) { 53 if (!Builder.isNamePreserving()) 54 return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt); 55 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt); 56} 57 58void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var, 59 llvm::Value *Init) { 60 llvm::StoreInst *Store = new llvm::StoreInst(Init, Var); 61 llvm::BasicBlock *Block = AllocaInsertPt->getParent(); 62 Block->getInstList().insertAfter(&*AllocaInsertPt, Store); 63} 64 65llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty, 66 const Twine &Name) { 67 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name); 68 // FIXME: Should we prefer the preferred type alignment here? 69 CharUnits Align = getContext().getTypeAlignInChars(Ty); 70 Alloc->setAlignment(Align.getQuantity()); 71 return Alloc; 72} 73 74llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty, 75 const Twine &Name) { 76 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name); 77 // FIXME: Should we prefer the preferred type alignment here? 78 CharUnits Align = getContext().getTypeAlignInChars(Ty); 79 Alloc->setAlignment(Align.getQuantity()); 80 return Alloc; 81} 82 83/// EvaluateExprAsBool - Perform the usual unary conversions on the specified 84/// expression and compare the result against zero, returning an Int1Ty value. 85llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) { 86 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) { 87 llvm::Value *MemPtr = EmitScalarExpr(E); 88 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT); 89 } 90 91 QualType BoolTy = getContext().BoolTy; 92 if (!E->getType()->isAnyComplexType()) 93 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy); 94 95 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy); 96} 97 98/// EmitIgnoredExpr - Emit code to compute the specified expression, 99/// ignoring the result. 100void CodeGenFunction::EmitIgnoredExpr(const Expr *E) { 101 if (E->isRValue()) 102 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true); 103 104 // Just emit it as an l-value and drop the result. 105 EmitLValue(E); 106} 107 108/// EmitAnyExpr - Emit code to compute the specified expression which 109/// can have any type. The result is returned as an RValue struct. 110/// If this is an aggregate expression, AggSlot indicates where the 111/// result should be returned. 112RValue CodeGenFunction::EmitAnyExpr(const Expr *E, 113 AggValueSlot aggSlot, 114 bool ignoreResult) { 115 if (!hasAggregateLLVMType(E->getType())) 116 return RValue::get(EmitScalarExpr(E, ignoreResult)); 117 else if (E->getType()->isAnyComplexType()) 118 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult)); 119 120 if (!ignoreResult && aggSlot.isIgnored()) 121 aggSlot = CreateAggTemp(E->getType(), "agg-temp"); 122 EmitAggExpr(E, aggSlot); 123 return aggSlot.asRValue(); 124} 125 126/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 127/// always be accessible even if no aggregate location is provided. 128RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) { 129 AggValueSlot AggSlot = AggValueSlot::ignored(); 130 131 if (hasAggregateLLVMType(E->getType()) && 132 !E->getType()->isAnyComplexType()) 133 AggSlot = CreateAggTemp(E->getType(), "agg.tmp"); 134 return EmitAnyExpr(E, AggSlot); 135} 136 137/// EmitAnyExprToMem - Evaluate an expression into a given memory 138/// location. 139void CodeGenFunction::EmitAnyExprToMem(const Expr *E, 140 llvm::Value *Location, 141 Qualifiers Quals, 142 bool IsInit) { 143 // FIXME: This function should take an LValue as an argument. 144 if (E->getType()->isAnyComplexType()) { 145 EmitComplexExprIntoAddr(E, Location, Quals.hasVolatile()); 146 } else if (hasAggregateLLVMType(E->getType())) { 147 CharUnits Alignment = getContext().getTypeAlignInChars(E->getType()); 148 EmitAggExpr(E, AggValueSlot::forAddr(Location, Alignment, Quals, 149 AggValueSlot::IsDestructed_t(IsInit), 150 AggValueSlot::DoesNotNeedGCBarriers, 151 AggValueSlot::IsAliased_t(!IsInit))); 152 } else { 153 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false)); 154 LValue LV = MakeAddrLValue(Location, E->getType()); 155 EmitStoreThroughLValue(RV, LV); 156 } 157} 158 159namespace { 160/// \brief An adjustment to be made to the temporary created when emitting a 161/// reference binding, which accesses a particular subobject of that temporary. 162 struct SubobjectAdjustment { 163 enum { 164 DerivedToBaseAdjustment, 165 FieldAdjustment, 166 MemberPointerAdjustment 167 } Kind; 168 169 union { 170 struct { 171 const CastExpr *BasePath; 172 const CXXRecordDecl *DerivedClass; 173 } DerivedToBase; 174 175 FieldDecl *Field; 176 177 struct { 178 const MemberPointerType *MPT; 179 llvm::Value *Ptr; 180 } Ptr; 181 }; 182 183 SubobjectAdjustment(const CastExpr *BasePath, 184 const CXXRecordDecl *DerivedClass) 185 : Kind(DerivedToBaseAdjustment) { 186 DerivedToBase.BasePath = BasePath; 187 DerivedToBase.DerivedClass = DerivedClass; 188 } 189 190 SubobjectAdjustment(FieldDecl *Field) 191 : Kind(FieldAdjustment) { 192 this->Field = Field; 193 } 194 195 SubobjectAdjustment(const MemberPointerType *MPT, llvm::Value *Ptr) 196 : Kind(MemberPointerAdjustment) { 197 this->Ptr.MPT = MPT; 198 this->Ptr.Ptr = Ptr; 199 } 200 }; 201} 202 203static llvm::Value * 204CreateReferenceTemporary(CodeGenFunction &CGF, QualType Type, 205 const NamedDecl *InitializedDecl) { 206 if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) { 207 if (VD->hasGlobalStorage()) { 208 SmallString<256> Name; 209 llvm::raw_svector_ostream Out(Name); 210 CGF.CGM.getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out); 211 Out.flush(); 212 213 llvm::Type *RefTempTy = CGF.ConvertTypeForMem(Type); 214 215 // Create the reference temporary. 216 llvm::GlobalValue *RefTemp = 217 new llvm::GlobalVariable(CGF.CGM.getModule(), 218 RefTempTy, /*isConstant=*/false, 219 llvm::GlobalValue::InternalLinkage, 220 llvm::Constant::getNullValue(RefTempTy), 221 Name.str()); 222 return RefTemp; 223 } 224 } 225 226 return CGF.CreateMemTemp(Type, "ref.tmp"); 227} 228 229static llvm::Value * 230EmitExprForReferenceBinding(CodeGenFunction &CGF, const Expr *E, 231 llvm::Value *&ReferenceTemporary, 232 const CXXDestructorDecl *&ReferenceTemporaryDtor, 233 QualType &ObjCARCReferenceLifetimeType, 234 const NamedDecl *InitializedDecl) { 235 // Look through single-element init lists that claim to be lvalues. They're 236 // just syntactic wrappers in this case. 237 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E)) { 238 if (ILE->getNumInits() == 1 && ILE->isGLValue()) 239 E = ILE->getInit(0); 240 } 241 242 // Look through expressions for materialized temporaries (for now). 243 if (const MaterializeTemporaryExpr *M 244 = dyn_cast<MaterializeTemporaryExpr>(E)) { 245 // Objective-C++ ARC: 246 // If we are binding a reference to a temporary that has ownership, we 247 // need to perform retain/release operations on the temporary. 248 if (CGF.getContext().getLangOpts().ObjCAutoRefCount && 249 E->getType()->isObjCLifetimeType() && 250 (E->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 251 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak || 252 E->getType().getObjCLifetime() == Qualifiers::OCL_Autoreleasing)) 253 ObjCARCReferenceLifetimeType = E->getType(); 254 255 E = M->GetTemporaryExpr(); 256 } 257 258 if (const CXXDefaultArgExpr *DAE = dyn_cast<CXXDefaultArgExpr>(E)) 259 E = DAE->getExpr(); 260 261 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(E)) { 262 CGF.enterFullExpression(EWC); 263 CodeGenFunction::RunCleanupsScope Scope(CGF); 264 265 return EmitExprForReferenceBinding(CGF, EWC->getSubExpr(), 266 ReferenceTemporary, 267 ReferenceTemporaryDtor, 268 ObjCARCReferenceLifetimeType, 269 InitializedDecl); 270 } 271 272 RValue RV; 273 if (E->isGLValue()) { 274 // Emit the expression as an lvalue. 275 LValue LV = CGF.EmitLValue(E); 276 277 if (LV.isSimple()) 278 return LV.getAddress(); 279 280 // We have to load the lvalue. 281 RV = CGF.EmitLoadOfLValue(LV); 282 } else { 283 if (!ObjCARCReferenceLifetimeType.isNull()) { 284 ReferenceTemporary = CreateReferenceTemporary(CGF, 285 ObjCARCReferenceLifetimeType, 286 InitializedDecl); 287 288 289 LValue RefTempDst = CGF.MakeAddrLValue(ReferenceTemporary, 290 ObjCARCReferenceLifetimeType); 291 292 CGF.EmitScalarInit(E, dyn_cast_or_null<ValueDecl>(InitializedDecl), 293 RefTempDst, false); 294 295 bool ExtendsLifeOfTemporary = false; 296 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(InitializedDecl)) { 297 if (Var->extendsLifetimeOfTemporary()) 298 ExtendsLifeOfTemporary = true; 299 } else if (InitializedDecl && isa<FieldDecl>(InitializedDecl)) { 300 ExtendsLifeOfTemporary = true; 301 } 302 303 if (!ExtendsLifeOfTemporary) { 304 // Since the lifetime of this temporary isn't going to be extended, 305 // we need to clean it up ourselves at the end of the full expression. 306 switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) { 307 case Qualifiers::OCL_None: 308 case Qualifiers::OCL_ExplicitNone: 309 case Qualifiers::OCL_Autoreleasing: 310 break; 311 312 case Qualifiers::OCL_Strong: { 313 assert(!ObjCARCReferenceLifetimeType->isArrayType()); 314 CleanupKind cleanupKind = CGF.getARCCleanupKind(); 315 CGF.pushDestroy(cleanupKind, 316 ReferenceTemporary, 317 ObjCARCReferenceLifetimeType, 318 CodeGenFunction::destroyARCStrongImprecise, 319 cleanupKind & EHCleanup); 320 break; 321 } 322 323 case Qualifiers::OCL_Weak: 324 assert(!ObjCARCReferenceLifetimeType->isArrayType()); 325 CGF.pushDestroy(NormalAndEHCleanup, 326 ReferenceTemporary, 327 ObjCARCReferenceLifetimeType, 328 CodeGenFunction::destroyARCWeak, 329 /*useEHCleanupForArray*/ true); 330 break; 331 } 332 333 ObjCARCReferenceLifetimeType = QualType(); 334 } 335 336 return ReferenceTemporary; 337 } 338 339 SmallVector<SubobjectAdjustment, 2> Adjustments; 340 while (true) { 341 E = E->IgnoreParens(); 342 343 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 344 if ((CE->getCastKind() == CK_DerivedToBase || 345 CE->getCastKind() == CK_UncheckedDerivedToBase) && 346 E->getType()->isRecordType()) { 347 E = CE->getSubExpr(); 348 CXXRecordDecl *Derived 349 = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl()); 350 Adjustments.push_back(SubobjectAdjustment(CE, Derived)); 351 continue; 352 } 353 354 if (CE->getCastKind() == CK_NoOp) { 355 E = CE->getSubExpr(); 356 continue; 357 } 358 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 359 if (!ME->isArrow() && ME->getBase()->isRValue()) { 360 assert(ME->getBase()->getType()->isRecordType()); 361 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 362 E = ME->getBase(); 363 Adjustments.push_back(SubobjectAdjustment(Field)); 364 continue; 365 } 366 } 367 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 368 if (BO->isPtrMemOp()) { 369 assert(BO->getLHS()->isRValue()); 370 E = BO->getLHS(); 371 const MemberPointerType *MPT = 372 BO->getRHS()->getType()->getAs<MemberPointerType>(); 373 llvm::Value *Ptr = CGF.EmitScalarExpr(BO->getRHS()); 374 Adjustments.push_back(SubobjectAdjustment(MPT, Ptr)); 375 } 376 } 377 378 if (const OpaqueValueExpr *opaque = dyn_cast<OpaqueValueExpr>(E)) 379 if (opaque->getType()->isRecordType()) 380 return CGF.EmitOpaqueValueLValue(opaque).getAddress(); 381 382 // Nothing changed. 383 break; 384 } 385 386 // Create a reference temporary if necessary. 387 AggValueSlot AggSlot = AggValueSlot::ignored(); 388 if (CGF.hasAggregateLLVMType(E->getType()) && 389 !E->getType()->isAnyComplexType()) { 390 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(), 391 InitializedDecl); 392 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(E->getType()); 393 AggValueSlot::IsDestructed_t isDestructed 394 = AggValueSlot::IsDestructed_t(InitializedDecl != 0); 395 AggSlot = AggValueSlot::forAddr(ReferenceTemporary, Alignment, 396 Qualifiers(), isDestructed, 397 AggValueSlot::DoesNotNeedGCBarriers, 398 AggValueSlot::IsNotAliased); 399 } 400 401 if (InitializedDecl) { 402 // Get the destructor for the reference temporary. 403 if (const RecordType *RT = E->getType()->getAs<RecordType>()) { 404 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 405 if (!ClassDecl->hasTrivialDestructor()) 406 ReferenceTemporaryDtor = ClassDecl->getDestructor(); 407 } 408 } 409 410 RV = CGF.EmitAnyExpr(E, AggSlot); 411 412 // Check if need to perform derived-to-base casts and/or field accesses, to 413 // get from the temporary object we created (and, potentially, for which we 414 // extended the lifetime) to the subobject we're binding the reference to. 415 if (!Adjustments.empty()) { 416 llvm::Value *Object = RV.getAggregateAddr(); 417 for (unsigned I = Adjustments.size(); I != 0; --I) { 418 SubobjectAdjustment &Adjustment = Adjustments[I-1]; 419 switch (Adjustment.Kind) { 420 case SubobjectAdjustment::DerivedToBaseAdjustment: 421 Object = 422 CGF.GetAddressOfBaseClass(Object, 423 Adjustment.DerivedToBase.DerivedClass, 424 Adjustment.DerivedToBase.BasePath->path_begin(), 425 Adjustment.DerivedToBase.BasePath->path_end(), 426 /*NullCheckValue=*/false); 427 break; 428 429 case SubobjectAdjustment::FieldAdjustment: { 430 LValue LV = CGF.MakeAddrLValue(Object, E->getType()); 431 LV = CGF.EmitLValueForField(LV, Adjustment.Field); 432 if (LV.isSimple()) { 433 Object = LV.getAddress(); 434 break; 435 } 436 437 // For non-simple lvalues, we actually have to create a copy of 438 // the object we're binding to. 439 QualType T = Adjustment.Field->getType().getNonReferenceType() 440 .getUnqualifiedType(); 441 Object = CreateReferenceTemporary(CGF, T, InitializedDecl); 442 LValue TempLV = CGF.MakeAddrLValue(Object, 443 Adjustment.Field->getType()); 444 CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV), TempLV); 445 break; 446 } 447 448 case SubobjectAdjustment::MemberPointerAdjustment: { 449 Object = CGF.CGM.getCXXABI().EmitMemberDataPointerAddress( 450 CGF, Object, Adjustment.Ptr.Ptr, Adjustment.Ptr.MPT); 451 break; 452 } 453 } 454 } 455 456 return Object; 457 } 458 } 459 460 if (RV.isAggregate()) 461 return RV.getAggregateAddr(); 462 463 // Create a temporary variable that we can bind the reference to. 464 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(), 465 InitializedDecl); 466 467 468 unsigned Alignment = 469 CGF.getContext().getTypeAlignInChars(E->getType()).getQuantity(); 470 if (RV.isScalar()) 471 CGF.EmitStoreOfScalar(RV.getScalarVal(), ReferenceTemporary, 472 /*Volatile=*/false, Alignment, E->getType()); 473 else 474 CGF.StoreComplexToAddr(RV.getComplexVal(), ReferenceTemporary, 475 /*Volatile=*/false); 476 return ReferenceTemporary; 477} 478 479RValue 480CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E, 481 const NamedDecl *InitializedDecl) { 482 llvm::Value *ReferenceTemporary = 0; 483 const CXXDestructorDecl *ReferenceTemporaryDtor = 0; 484 QualType ObjCARCReferenceLifetimeType; 485 llvm::Value *Value = EmitExprForReferenceBinding(*this, E, ReferenceTemporary, 486 ReferenceTemporaryDtor, 487 ObjCARCReferenceLifetimeType, 488 InitializedDecl); 489 if (CatchUndefined && !E->getType()->isFunctionType()) { 490 // C++11 [dcl.ref]p5 (as amended by core issue 453): 491 // If a glvalue to which a reference is directly bound designates neither 492 // an existing object or function of an appropriate type nor a region of 493 // storage of suitable size and alignment to contain an object of the 494 // reference's type, the behavior is undefined. 495 QualType Ty = E->getType(); 496 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty); 497 } 498 if (!ReferenceTemporaryDtor && ObjCARCReferenceLifetimeType.isNull()) 499 return RValue::get(Value); 500 501 // Make sure to call the destructor for the reference temporary. 502 const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl); 503 if (VD && VD->hasGlobalStorage()) { 504 if (ReferenceTemporaryDtor) { 505 llvm::Constant *DtorFn = 506 CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete); 507 CGM.getCXXABI().registerGlobalDtor(*this, DtorFn, 508 cast<llvm::Constant>(ReferenceTemporary)); 509 } else { 510 assert(!ObjCARCReferenceLifetimeType.isNull()); 511 // Note: We intentionally do not register a global "destructor" to 512 // release the object. 513 } 514 515 return RValue::get(Value); 516 } 517 518 if (ReferenceTemporaryDtor) 519 PushDestructorCleanup(ReferenceTemporaryDtor, ReferenceTemporary); 520 else { 521 switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) { 522 case Qualifiers::OCL_None: 523 llvm_unreachable( 524 "Not a reference temporary that needs to be deallocated"); 525 case Qualifiers::OCL_ExplicitNone: 526 case Qualifiers::OCL_Autoreleasing: 527 // Nothing to do. 528 break; 529 530 case Qualifiers::OCL_Strong: { 531 bool precise = VD && VD->hasAttr<ObjCPreciseLifetimeAttr>(); 532 CleanupKind cleanupKind = getARCCleanupKind(); 533 pushDestroy(cleanupKind, ReferenceTemporary, ObjCARCReferenceLifetimeType, 534 precise ? destroyARCStrongPrecise : destroyARCStrongImprecise, 535 cleanupKind & EHCleanup); 536 break; 537 } 538 539 case Qualifiers::OCL_Weak: { 540 // __weak objects always get EH cleanups; otherwise, exceptions 541 // could cause really nasty crashes instead of mere leaks. 542 pushDestroy(NormalAndEHCleanup, ReferenceTemporary, 543 ObjCARCReferenceLifetimeType, destroyARCWeak, true); 544 break; 545 } 546 } 547 } 548 549 return RValue::get(Value); 550} 551 552 553/// getAccessedFieldNo - Given an encoded value and a result number, return the 554/// input field number being accessed. 555unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx, 556 const llvm::Constant *Elts) { 557 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx)) 558 ->getZExtValue(); 559} 560 561void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, 562 llvm::Value *Address, 563 QualType Ty, CharUnits Alignment) { 564 if (!CatchUndefined) 565 return; 566 567 llvm::Value *Cond = 0; 568 569 if (TCK != TCK_Load && TCK != TCK_Store) { 570 // The glvalue must not be an empty glvalue. Don't bother checking this for 571 // loads and stores, because we will get a segfault anyway (if the operation 572 // isn't optimized out). 573 Cond = Builder.CreateICmpNE( 574 Address, llvm::Constant::getNullValue(Address->getType())); 575 } 576 577 uint64_t AlignVal = Alignment.getQuantity(); 578 579 if (!Ty->isIncompleteType()) { 580 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity(); 581 if (!AlignVal) 582 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity(); 583 584 // This needs to be to the standard address space. 585 Address = Builder.CreateBitCast(Address, Int8PtrTy); 586 587 // The glvalue must refer to a large enough storage region. 588 // FIXME: If -faddress-sanitizer is enabled, insert dynamic instrumentation 589 // to check this. 590 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, IntPtrTy); 591 llvm::Value *Min = Builder.getFalse(); 592 llvm::Value *LargeEnough = 593 Builder.CreateICmpUGE(Builder.CreateCall2(F, Address, Min), 594 llvm::ConstantInt::get(IntPtrTy, Size)); 595 Cond = Cond ? Builder.CreateAnd(Cond, LargeEnough) : LargeEnough; 596 } 597 598 if (AlignVal) { 599 // The glvalue must be suitably aligned. 600 llvm::Value *Align = 601 Builder.CreateAnd(Builder.CreatePtrToInt(Address, IntPtrTy), 602 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1)); 603 Cond = Builder.CreateAnd(Cond, 604 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0))); 605 } 606 607 if (Cond) { 608 llvm::Constant *StaticData[] = { 609 EmitCheckSourceLocation(Loc), 610 EmitCheckTypeDescriptor(Ty), 611 llvm::ConstantInt::get(SizeTy, AlignVal), 612 llvm::ConstantInt::get(Int8Ty, TCK) 613 }; 614 EmitCheck(Cond, "type_mismatch", StaticData, Address); 615 } 616} 617 618 619CodeGenFunction::ComplexPairTy CodeGenFunction:: 620EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 621 bool isInc, bool isPre) { 622 ComplexPairTy InVal = LoadComplexFromAddr(LV.getAddress(), 623 LV.isVolatileQualified()); 624 625 llvm::Value *NextVal; 626 if (isa<llvm::IntegerType>(InVal.first->getType())) { 627 uint64_t AmountVal = isInc ? 1 : -1; 628 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true); 629 630 // Add the inc/dec to the real part. 631 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec"); 632 } else { 633 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType(); 634 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1); 635 if (!isInc) 636 FVal.changeSign(); 637 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal); 638 639 // Add the inc/dec to the real part. 640 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec"); 641 } 642 643 ComplexPairTy IncVal(NextVal, InVal.second); 644 645 // Store the updated result through the lvalue. 646 StoreComplexToAddr(IncVal, LV.getAddress(), LV.isVolatileQualified()); 647 648 // If this is a postinc, return the value read from memory, otherwise use the 649 // updated value. 650 return isPre ? IncVal : InVal; 651} 652 653 654//===----------------------------------------------------------------------===// 655// LValue Expression Emission 656//===----------------------------------------------------------------------===// 657 658RValue CodeGenFunction::GetUndefRValue(QualType Ty) { 659 if (Ty->isVoidType()) 660 return RValue::get(0); 661 662 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 663 llvm::Type *EltTy = ConvertType(CTy->getElementType()); 664 llvm::Value *U = llvm::UndefValue::get(EltTy); 665 return RValue::getComplex(std::make_pair(U, U)); 666 } 667 668 // If this is a use of an undefined aggregate type, the aggregate must have an 669 // identifiable address. Just because the contents of the value are undefined 670 // doesn't mean that the address can't be taken and compared. 671 if (hasAggregateLLVMType(Ty)) { 672 llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp"); 673 return RValue::getAggregate(DestPtr); 674 } 675 676 return RValue::get(llvm::UndefValue::get(ConvertType(Ty))); 677} 678 679RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E, 680 const char *Name) { 681 ErrorUnsupported(E, Name); 682 return GetUndefRValue(E->getType()); 683} 684 685LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E, 686 const char *Name) { 687 ErrorUnsupported(E, Name); 688 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType())); 689 return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType()); 690} 691 692LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) { 693 LValue LV = EmitLValue(E); 694 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) 695 EmitTypeCheck(TCK, E->getExprLoc(), LV.getAddress(), 696 E->getType(), LV.getAlignment()); 697 return LV; 698} 699 700/// EmitLValue - Emit code to compute a designator that specifies the location 701/// of the expression. 702/// 703/// This can return one of two things: a simple address or a bitfield reference. 704/// In either case, the LLVM Value* in the LValue structure is guaranteed to be 705/// an LLVM pointer type. 706/// 707/// If this returns a bitfield reference, nothing about the pointee type of the 708/// LLVM value is known: For example, it may not be a pointer to an integer. 709/// 710/// If this returns a normal address, and if the lvalue's C type is fixed size, 711/// this method guarantees that the returned pointer type will point to an LLVM 712/// type of the same size of the lvalue's type. If the lvalue has a variable 713/// length type, this is not possible. 714/// 715LValue CodeGenFunction::EmitLValue(const Expr *E) { 716 switch (E->getStmtClass()) { 717 default: return EmitUnsupportedLValue(E, "l-value expression"); 718 719 case Expr::ObjCPropertyRefExprClass: 720 llvm_unreachable("cannot emit a property reference directly"); 721 722 case Expr::ObjCSelectorExprClass: 723 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E)); 724 case Expr::ObjCIsaExprClass: 725 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E)); 726 case Expr::BinaryOperatorClass: 727 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E)); 728 case Expr::CompoundAssignOperatorClass: 729 if (!E->getType()->isAnyComplexType()) 730 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E)); 731 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E)); 732 case Expr::CallExprClass: 733 case Expr::CXXMemberCallExprClass: 734 case Expr::CXXOperatorCallExprClass: 735 case Expr::UserDefinedLiteralClass: 736 return EmitCallExprLValue(cast<CallExpr>(E)); 737 case Expr::VAArgExprClass: 738 return EmitVAArgExprLValue(cast<VAArgExpr>(E)); 739 case Expr::DeclRefExprClass: 740 return EmitDeclRefLValue(cast<DeclRefExpr>(E)); 741 case Expr::ParenExprClass: 742 return EmitLValue(cast<ParenExpr>(E)->getSubExpr()); 743 case Expr::GenericSelectionExprClass: 744 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr()); 745 case Expr::PredefinedExprClass: 746 return EmitPredefinedLValue(cast<PredefinedExpr>(E)); 747 case Expr::StringLiteralClass: 748 return EmitStringLiteralLValue(cast<StringLiteral>(E)); 749 case Expr::ObjCEncodeExprClass: 750 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E)); 751 case Expr::PseudoObjectExprClass: 752 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E)); 753 case Expr::InitListExprClass: 754 return EmitInitListLValue(cast<InitListExpr>(E)); 755 case Expr::CXXTemporaryObjectExprClass: 756 case Expr::CXXConstructExprClass: 757 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E)); 758 case Expr::CXXBindTemporaryExprClass: 759 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E)); 760 case Expr::LambdaExprClass: 761 return EmitLambdaLValue(cast<LambdaExpr>(E)); 762 763 case Expr::ExprWithCleanupsClass: { 764 const ExprWithCleanups *cleanups = cast<ExprWithCleanups>(E); 765 enterFullExpression(cleanups); 766 RunCleanupsScope Scope(*this); 767 return EmitLValue(cleanups->getSubExpr()); 768 } 769 770 case Expr::CXXScalarValueInitExprClass: 771 return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E)); 772 case Expr::CXXDefaultArgExprClass: 773 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr()); 774 case Expr::CXXTypeidExprClass: 775 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E)); 776 777 case Expr::ObjCMessageExprClass: 778 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E)); 779 case Expr::ObjCIvarRefExprClass: 780 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E)); 781 case Expr::StmtExprClass: 782 return EmitStmtExprLValue(cast<StmtExpr>(E)); 783 case Expr::UnaryOperatorClass: 784 return EmitUnaryOpLValue(cast<UnaryOperator>(E)); 785 case Expr::ArraySubscriptExprClass: 786 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E)); 787 case Expr::ExtVectorElementExprClass: 788 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E)); 789 case Expr::MemberExprClass: 790 return EmitMemberExpr(cast<MemberExpr>(E)); 791 case Expr::CompoundLiteralExprClass: 792 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E)); 793 case Expr::ConditionalOperatorClass: 794 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E)); 795 case Expr::BinaryConditionalOperatorClass: 796 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E)); 797 case Expr::ChooseExprClass: 798 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext())); 799 case Expr::OpaqueValueExprClass: 800 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E)); 801 case Expr::SubstNonTypeTemplateParmExprClass: 802 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement()); 803 case Expr::ImplicitCastExprClass: 804 case Expr::CStyleCastExprClass: 805 case Expr::CXXFunctionalCastExprClass: 806 case Expr::CXXStaticCastExprClass: 807 case Expr::CXXDynamicCastExprClass: 808 case Expr::CXXReinterpretCastExprClass: 809 case Expr::CXXConstCastExprClass: 810 case Expr::ObjCBridgedCastExprClass: 811 return EmitCastLValue(cast<CastExpr>(E)); 812 813 case Expr::MaterializeTemporaryExprClass: 814 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E)); 815 } 816} 817 818/// Given an object of the given canonical type, can we safely copy a 819/// value out of it based on its initializer? 820static bool isConstantEmittableObjectType(QualType type) { 821 assert(type.isCanonical()); 822 assert(!type->isReferenceType()); 823 824 // Must be const-qualified but non-volatile. 825 Qualifiers qs = type.getLocalQualifiers(); 826 if (!qs.hasConst() || qs.hasVolatile()) return false; 827 828 // Otherwise, all object types satisfy this except C++ classes with 829 // mutable subobjects or non-trivial copy/destroy behavior. 830 if (const RecordType *RT = dyn_cast<RecordType>(type)) 831 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 832 if (RD->hasMutableFields() || !RD->isTrivial()) 833 return false; 834 835 return true; 836} 837 838/// Can we constant-emit a load of a reference to a variable of the 839/// given type? This is different from predicates like 840/// Decl::isUsableInConstantExpressions because we do want it to apply 841/// in situations that don't necessarily satisfy the language's rules 842/// for this (e.g. C++'s ODR-use rules). For example, we want to able 843/// to do this with const float variables even if those variables 844/// aren't marked 'constexpr'. 845enum ConstantEmissionKind { 846 CEK_None, 847 CEK_AsReferenceOnly, 848 CEK_AsValueOrReference, 849 CEK_AsValueOnly 850}; 851static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) { 852 type = type.getCanonicalType(); 853 if (const ReferenceType *ref = dyn_cast<ReferenceType>(type)) { 854 if (isConstantEmittableObjectType(ref->getPointeeType())) 855 return CEK_AsValueOrReference; 856 return CEK_AsReferenceOnly; 857 } 858 if (isConstantEmittableObjectType(type)) 859 return CEK_AsValueOnly; 860 return CEK_None; 861} 862 863/// Try to emit a reference to the given value without producing it as 864/// an l-value. This is actually more than an optimization: we can't 865/// produce an l-value for variables that we never actually captured 866/// in a block or lambda, which means const int variables or constexpr 867/// literals or similar. 868CodeGenFunction::ConstantEmission 869CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) { 870 ValueDecl *value = refExpr->getDecl(); 871 872 // The value needs to be an enum constant or a constant variable. 873 ConstantEmissionKind CEK; 874 if (isa<ParmVarDecl>(value)) { 875 CEK = CEK_None; 876 } else if (VarDecl *var = dyn_cast<VarDecl>(value)) { 877 CEK = checkVarTypeForConstantEmission(var->getType()); 878 } else if (isa<EnumConstantDecl>(value)) { 879 CEK = CEK_AsValueOnly; 880 } else { 881 CEK = CEK_None; 882 } 883 if (CEK == CEK_None) return ConstantEmission(); 884 885 Expr::EvalResult result; 886 bool resultIsReference; 887 QualType resultType; 888 889 // It's best to evaluate all the way as an r-value if that's permitted. 890 if (CEK != CEK_AsReferenceOnly && 891 refExpr->EvaluateAsRValue(result, getContext())) { 892 resultIsReference = false; 893 resultType = refExpr->getType(); 894 895 // Otherwise, try to evaluate as an l-value. 896 } else if (CEK != CEK_AsValueOnly && 897 refExpr->EvaluateAsLValue(result, getContext())) { 898 resultIsReference = true; 899 resultType = value->getType(); 900 901 // Failure. 902 } else { 903 return ConstantEmission(); 904 } 905 906 // In any case, if the initializer has side-effects, abandon ship. 907 if (result.HasSideEffects) 908 return ConstantEmission(); 909 910 // Emit as a constant. 911 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this); 912 913 // Make sure we emit a debug reference to the global variable. 914 // This should probably fire even for 915 if (isa<VarDecl>(value)) { 916 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value))) 917 EmitDeclRefExprDbgValue(refExpr, C); 918 } else { 919 assert(isa<EnumConstantDecl>(value)); 920 EmitDeclRefExprDbgValue(refExpr, C); 921 } 922 923 // If we emitted a reference constant, we need to dereference that. 924 if (resultIsReference) 925 return ConstantEmission::forReference(C); 926 927 return ConstantEmission::forValue(C); 928} 929 930llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue) { 931 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(), 932 lvalue.getAlignment().getQuantity(), 933 lvalue.getType(), lvalue.getTBAAInfo()); 934} 935 936static bool hasBooleanRepresentation(QualType Ty) { 937 if (Ty->isBooleanType()) 938 return true; 939 940 if (const EnumType *ET = Ty->getAs<EnumType>()) 941 return ET->getDecl()->getIntegerType()->isBooleanType(); 942 943 if (const AtomicType *AT = Ty->getAs<AtomicType>()) 944 return hasBooleanRepresentation(AT->getValueType()); 945 946 return false; 947} 948 949llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) { 950 const EnumType *ET = Ty->getAs<EnumType>(); 951 bool IsRegularCPlusPlusEnum = (getLangOpts().CPlusPlus && ET && 952 CGM.getCodeGenOpts().StrictEnums && 953 !ET->getDecl()->isFixed()); 954 bool IsBool = hasBooleanRepresentation(Ty); 955 if (!IsBool && !IsRegularCPlusPlusEnum) 956 return NULL; 957 958 llvm::APInt Min; 959 llvm::APInt End; 960 if (IsBool) { 961 Min = llvm::APInt(8, 0); 962 End = llvm::APInt(8, 2); 963 } else { 964 const EnumDecl *ED = ET->getDecl(); 965 llvm::Type *LTy = ConvertTypeForMem(ED->getIntegerType()); 966 unsigned Bitwidth = LTy->getScalarSizeInBits(); 967 unsigned NumNegativeBits = ED->getNumNegativeBits(); 968 unsigned NumPositiveBits = ED->getNumPositiveBits(); 969 970 if (NumNegativeBits) { 971 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1); 972 assert(NumBits <= Bitwidth); 973 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1); 974 Min = -End; 975 } else { 976 assert(NumPositiveBits <= Bitwidth); 977 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits; 978 Min = llvm::APInt(Bitwidth, 0); 979 } 980 } 981 982 llvm::MDBuilder MDHelper(getLLVMContext()); 983 return MDHelper.createRange(Min, End); 984} 985 986llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile, 987 unsigned Alignment, QualType Ty, 988 llvm::MDNode *TBAAInfo) { 989 990 // For better performance, handle vector loads differently. 991 if (Ty->isVectorType()) { 992 llvm::Value *V; 993 const llvm::Type *EltTy = 994 cast<llvm::PointerType>(Addr->getType())->getElementType(); 995 996 const llvm::VectorType *VTy = cast<llvm::VectorType>(EltTy); 997 998 // Handle vectors of size 3, like size 4 for better performance. 999 if (VTy->getNumElements() == 3) { 1000 1001 // Bitcast to vec4 type. 1002 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(), 1003 4); 1004 llvm::PointerType *ptVec4Ty = 1005 llvm::PointerType::get(vec4Ty, 1006 (cast<llvm::PointerType>( 1007 Addr->getType()))->getAddressSpace()); 1008 llvm::Value *Cast = Builder.CreateBitCast(Addr, ptVec4Ty, 1009 "castToVec4"); 1010 // Now load value. 1011 llvm::Value *LoadVal = Builder.CreateLoad(Cast, Volatile, "loadVec4"); 1012 1013 // Shuffle vector to get vec3. 1014 llvm::SmallVector<llvm::Constant*, 3> Mask; 1015 Mask.push_back(llvm::ConstantInt::get( 1016 llvm::Type::getInt32Ty(getLLVMContext()), 1017 0)); 1018 Mask.push_back(llvm::ConstantInt::get( 1019 llvm::Type::getInt32Ty(getLLVMContext()), 1020 1)); 1021 Mask.push_back(llvm::ConstantInt::get( 1022 llvm::Type::getInt32Ty(getLLVMContext()), 1023 2)); 1024 1025 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1026 V = Builder.CreateShuffleVector(LoadVal, 1027 llvm::UndefValue::get(vec4Ty), 1028 MaskV, "extractVec"); 1029 return EmitFromMemory(V, Ty); 1030 } 1031 } 1032 1033 llvm::LoadInst *Load = Builder.CreateLoad(Addr); 1034 if (Volatile) 1035 Load->setVolatile(true); 1036 if (Alignment) 1037 Load->setAlignment(Alignment); 1038 if (TBAAInfo) 1039 CGM.DecorateInstruction(Load, TBAAInfo); 1040 // If this is an atomic type, all normal reads must be atomic 1041 if (Ty->isAtomicType()) 1042 Load->setAtomic(llvm::SequentiallyConsistent); 1043 1044 if (CGM.getCodeGenOpts().OptimizationLevel > 0) 1045 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty)) 1046 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo); 1047 1048 return EmitFromMemory(Load, Ty); 1049} 1050 1051llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) { 1052 // Bool has a different representation in memory than in registers. 1053 if (hasBooleanRepresentation(Ty)) { 1054 // This should really always be an i1, but sometimes it's already 1055 // an i8, and it's awkward to track those cases down. 1056 if (Value->getType()->isIntegerTy(1)) 1057 return Builder.CreateZExt(Value, Builder.getInt8Ty(), "frombool"); 1058 assert(Value->getType()->isIntegerTy(8) && "value rep of bool not i1/i8"); 1059 } 1060 1061 return Value; 1062} 1063 1064llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) { 1065 // Bool has a different representation in memory than in registers. 1066 if (hasBooleanRepresentation(Ty)) { 1067 assert(Value->getType()->isIntegerTy(8) && "memory rep of bool not i8"); 1068 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool"); 1069 } 1070 1071 return Value; 1072} 1073 1074void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr, 1075 bool Volatile, unsigned Alignment, 1076 QualType Ty, 1077 llvm::MDNode *TBAAInfo, 1078 bool isInit) { 1079 1080 // Handle vectors differently to get better performance. 1081 if (Ty->isVectorType()) { 1082 llvm::Type *SrcTy = Value->getType(); 1083 llvm::VectorType *VecTy = cast<llvm::VectorType>(SrcTy); 1084 // Handle vec3 special. 1085 if (VecTy->getNumElements() == 3) { 1086 llvm::LLVMContext &VMContext = getLLVMContext(); 1087 1088 // Our source is a vec3, do a shuffle vector to make it a vec4. 1089 llvm::SmallVector<llvm::Constant*, 4> Mask; 1090 Mask.push_back(llvm::ConstantInt::get( 1091 llvm::Type::getInt32Ty(VMContext), 1092 0)); 1093 Mask.push_back(llvm::ConstantInt::get( 1094 llvm::Type::getInt32Ty(VMContext), 1095 1)); 1096 Mask.push_back(llvm::ConstantInt::get( 1097 llvm::Type::getInt32Ty(VMContext), 1098 2)); 1099 Mask.push_back(llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext))); 1100 1101 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1102 Value = Builder.CreateShuffleVector(Value, 1103 llvm::UndefValue::get(VecTy), 1104 MaskV, "extractVec"); 1105 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4); 1106 } 1107 llvm::PointerType *DstPtr = cast<llvm::PointerType>(Addr->getType()); 1108 if (DstPtr->getElementType() != SrcTy) { 1109 llvm::Type *MemTy = 1110 llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace()); 1111 Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp"); 1112 } 1113 } 1114 1115 Value = EmitToMemory(Value, Ty); 1116 1117 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile); 1118 if (Alignment) 1119 Store->setAlignment(Alignment); 1120 if (TBAAInfo) 1121 CGM.DecorateInstruction(Store, TBAAInfo); 1122 if (!isInit && Ty->isAtomicType()) 1123 Store->setAtomic(llvm::SequentiallyConsistent); 1124} 1125 1126void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue, 1127 bool isInit) { 1128 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(), 1129 lvalue.getAlignment().getQuantity(), lvalue.getType(), 1130 lvalue.getTBAAInfo(), isInit); 1131} 1132 1133/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this 1134/// method emits the address of the lvalue, then loads the result as an rvalue, 1135/// returning the rvalue. 1136RValue CodeGenFunction::EmitLoadOfLValue(LValue LV) { 1137 if (LV.isObjCWeak()) { 1138 // load of a __weak object. 1139 llvm::Value *AddrWeakObj = LV.getAddress(); 1140 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this, 1141 AddrWeakObj)); 1142 } 1143 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) 1144 return RValue::get(EmitARCLoadWeak(LV.getAddress())); 1145 1146 if (LV.isSimple()) { 1147 assert(!LV.getType()->isFunctionType()); 1148 1149 // Everything needs a load. 1150 return RValue::get(EmitLoadOfScalar(LV)); 1151 } 1152 1153 if (LV.isVectorElt()) { 1154 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddr(), 1155 LV.isVolatileQualified()); 1156 Load->setAlignment(LV.getAlignment().getQuantity()); 1157 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(), 1158 "vecext")); 1159 } 1160 1161 // If this is a reference to a subset of the elements of a vector, either 1162 // shuffle the input or extract/insert them as appropriate. 1163 if (LV.isExtVectorElt()) 1164 return EmitLoadOfExtVectorElementLValue(LV); 1165 1166 assert(LV.isBitField() && "Unknown LValue type!"); 1167 return EmitLoadOfBitfieldLValue(LV); 1168} 1169 1170RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) { 1171 const CGBitFieldInfo &Info = LV.getBitFieldInfo(); 1172 1173 // Get the output type. 1174 llvm::Type *ResLTy = ConvertType(LV.getType()); 1175 unsigned ResSizeInBits = CGM.getDataLayout().getTypeSizeInBits(ResLTy); 1176 1177 // Compute the result as an OR of all of the individual component accesses. 1178 llvm::Value *Res = 0; 1179 for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) { 1180 const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i); 1181 CharUnits AccessAlignment = AI.AccessAlignment; 1182 if (!LV.getAlignment().isZero()) 1183 AccessAlignment = std::min(AccessAlignment, LV.getAlignment()); 1184 1185 // Get the field pointer. 1186 llvm::Value *Ptr = LV.getBitFieldBaseAddr(); 1187 1188 // Only offset by the field index if used, so that incoming values are not 1189 // required to be structures. 1190 if (AI.FieldIndex) 1191 Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field"); 1192 1193 // Offset by the byte offset, if used. 1194 if (!AI.FieldByteOffset.isZero()) { 1195 Ptr = EmitCastToVoidPtr(Ptr); 1196 Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset.getQuantity(), 1197 "bf.field.offs"); 1198 } 1199 1200 // Cast to the access type. 1201 llvm::Type *PTy = llvm::Type::getIntNPtrTy(getLLVMContext(), AI.AccessWidth, 1202 CGM.getContext().getTargetAddressSpace(LV.getType())); 1203 Ptr = Builder.CreateBitCast(Ptr, PTy); 1204 1205 // Perform the load. 1206 llvm::LoadInst *Load = Builder.CreateLoad(Ptr, LV.isVolatileQualified()); 1207 Load->setAlignment(AccessAlignment.getQuantity()); 1208 1209 // Shift out unused low bits and mask out unused high bits. 1210 llvm::Value *Val = Load; 1211 if (AI.FieldBitStart) 1212 Val = Builder.CreateLShr(Load, AI.FieldBitStart); 1213 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(AI.AccessWidth, 1214 AI.TargetBitWidth), 1215 "bf.clear"); 1216 1217 // Extend or truncate to the target size. 1218 if (AI.AccessWidth < ResSizeInBits) 1219 Val = Builder.CreateZExt(Val, ResLTy); 1220 else if (AI.AccessWidth > ResSizeInBits) 1221 Val = Builder.CreateTrunc(Val, ResLTy); 1222 1223 // Shift into place, and OR into the result. 1224 if (AI.TargetBitOffset) 1225 Val = Builder.CreateShl(Val, AI.TargetBitOffset); 1226 Res = Res ? Builder.CreateOr(Res, Val) : Val; 1227 } 1228 1229 // If the bit-field is signed, perform the sign-extension. 1230 // 1231 // FIXME: This can easily be folded into the load of the high bits, which 1232 // could also eliminate the mask of high bits in some situations. 1233 if (Info.isSigned()) { 1234 unsigned ExtraBits = ResSizeInBits - Info.getSize(); 1235 if (ExtraBits) 1236 Res = Builder.CreateAShr(Builder.CreateShl(Res, ExtraBits), 1237 ExtraBits, "bf.val.sext"); 1238 } 1239 1240 return RValue::get(Res); 1241} 1242 1243// If this is a reference to a subset of the elements of a vector, create an 1244// appropriate shufflevector. 1245RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) { 1246 llvm::LoadInst *Load = Builder.CreateLoad(LV.getExtVectorAddr(), 1247 LV.isVolatileQualified()); 1248 Load->setAlignment(LV.getAlignment().getQuantity()); 1249 llvm::Value *Vec = Load; 1250 1251 const llvm::Constant *Elts = LV.getExtVectorElts(); 1252 1253 // If the result of the expression is a non-vector type, we must be extracting 1254 // a single element. Just codegen as an extractelement. 1255 const VectorType *ExprVT = LV.getType()->getAs<VectorType>(); 1256 if (!ExprVT) { 1257 unsigned InIdx = getAccessedFieldNo(0, Elts); 1258 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx); 1259 return RValue::get(Builder.CreateExtractElement(Vec, Elt)); 1260 } 1261 1262 // Always use shuffle vector to try to retain the original program structure 1263 unsigned NumResultElts = ExprVT->getNumElements(); 1264 1265 SmallVector<llvm::Constant*, 4> Mask; 1266 for (unsigned i = 0; i != NumResultElts; ++i) 1267 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts))); 1268 1269 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1270 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()), 1271 MaskV); 1272 return RValue::get(Vec); 1273} 1274 1275 1276 1277/// EmitStoreThroughLValue - Store the specified rvalue into the specified 1278/// lvalue, where both are guaranteed to the have the same type, and that type 1279/// is 'Ty'. 1280void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit) { 1281 if (!Dst.isSimple()) { 1282 if (Dst.isVectorElt()) { 1283 // Read/modify/write the vector, inserting the new element. 1284 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getVectorAddr(), 1285 Dst.isVolatileQualified()); 1286 Load->setAlignment(Dst.getAlignment().getQuantity()); 1287 llvm::Value *Vec = Load; 1288 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(), 1289 Dst.getVectorIdx(), "vecins"); 1290 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getVectorAddr(), 1291 Dst.isVolatileQualified()); 1292 Store->setAlignment(Dst.getAlignment().getQuantity()); 1293 return; 1294 } 1295 1296 // If this is an update of extended vector elements, insert them as 1297 // appropriate. 1298 if (Dst.isExtVectorElt()) 1299 return EmitStoreThroughExtVectorComponentLValue(Src, Dst); 1300 1301 assert(Dst.isBitField() && "Unknown LValue type"); 1302 return EmitStoreThroughBitfieldLValue(Src, Dst); 1303 } 1304 1305 // There's special magic for assigning into an ARC-qualified l-value. 1306 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) { 1307 switch (Lifetime) { 1308 case Qualifiers::OCL_None: 1309 llvm_unreachable("present but none"); 1310 1311 case Qualifiers::OCL_ExplicitNone: 1312 // nothing special 1313 break; 1314 1315 case Qualifiers::OCL_Strong: 1316 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true); 1317 return; 1318 1319 case Qualifiers::OCL_Weak: 1320 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true); 1321 return; 1322 1323 case Qualifiers::OCL_Autoreleasing: 1324 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(), 1325 Src.getScalarVal())); 1326 // fall into the normal path 1327 break; 1328 } 1329 } 1330 1331 if (Dst.isObjCWeak() && !Dst.isNonGC()) { 1332 // load of a __weak object. 1333 llvm::Value *LvalueDst = Dst.getAddress(); 1334 llvm::Value *src = Src.getScalarVal(); 1335 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst); 1336 return; 1337 } 1338 1339 if (Dst.isObjCStrong() && !Dst.isNonGC()) { 1340 // load of a __strong object. 1341 llvm::Value *LvalueDst = Dst.getAddress(); 1342 llvm::Value *src = Src.getScalarVal(); 1343 if (Dst.isObjCIvar()) { 1344 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL"); 1345 llvm::Type *ResultType = ConvertType(getContext().LongTy); 1346 llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp()); 1347 llvm::Value *dst = RHS; 1348 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast"); 1349 llvm::Value *LHS = 1350 Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast"); 1351 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset"); 1352 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst, 1353 BytesBetween); 1354 } else if (Dst.isGlobalObjCRef()) { 1355 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst, 1356 Dst.isThreadLocalRef()); 1357 } 1358 else 1359 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst); 1360 return; 1361 } 1362 1363 assert(Src.isScalar() && "Can't emit an agg store with this method"); 1364 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit); 1365} 1366 1367void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 1368 llvm::Value **Result) { 1369 const CGBitFieldInfo &Info = Dst.getBitFieldInfo(); 1370 1371 // Get the output type. 1372 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType()); 1373 unsigned ResSizeInBits = CGM.getDataLayout().getTypeSizeInBits(ResLTy); 1374 1375 // Get the source value, truncated to the width of the bit-field. 1376 llvm::Value *SrcVal = Src.getScalarVal(); 1377 1378 if (hasBooleanRepresentation(Dst.getType())) 1379 SrcVal = Builder.CreateIntCast(SrcVal, ResLTy, /*IsSigned=*/false); 1380 1381 SrcVal = Builder.CreateAnd(SrcVal, llvm::APInt::getLowBitsSet(ResSizeInBits, 1382 Info.getSize()), 1383 "bf.value"); 1384 1385 // Return the new value of the bit-field, if requested. 1386 if (Result) { 1387 // Cast back to the proper type for result. 1388 llvm::Type *SrcTy = Src.getScalarVal()->getType(); 1389 llvm::Value *ReloadVal = Builder.CreateIntCast(SrcVal, SrcTy, false, 1390 "bf.reload.val"); 1391 1392 // Sign extend if necessary. 1393 if (Info.isSigned()) { 1394 unsigned ExtraBits = ResSizeInBits - Info.getSize(); 1395 if (ExtraBits) 1396 ReloadVal = Builder.CreateAShr(Builder.CreateShl(ReloadVal, ExtraBits), 1397 ExtraBits, "bf.reload.sext"); 1398 } 1399 1400 *Result = ReloadVal; 1401 } 1402 1403 // Iterate over the components, writing each piece to memory. 1404 for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) { 1405 const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i); 1406 CharUnits AccessAlignment = AI.AccessAlignment; 1407 if (!Dst.getAlignment().isZero()) 1408 AccessAlignment = std::min(AccessAlignment, Dst.getAlignment()); 1409 1410 // Get the field pointer. 1411 llvm::Value *Ptr = Dst.getBitFieldBaseAddr(); 1412 unsigned addressSpace = 1413 cast<llvm::PointerType>(Ptr->getType())->getAddressSpace(); 1414 1415 // Only offset by the field index if used, so that incoming values are not 1416 // required to be structures. 1417 if (AI.FieldIndex) 1418 Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field"); 1419 1420 // Offset by the byte offset, if used. 1421 if (!AI.FieldByteOffset.isZero()) { 1422 Ptr = EmitCastToVoidPtr(Ptr); 1423 Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset.getQuantity(), 1424 "bf.field.offs"); 1425 } 1426 1427 // Cast to the access type. 1428 llvm::Type *AccessLTy = 1429 llvm::Type::getIntNTy(getLLVMContext(), AI.AccessWidth); 1430 1431 llvm::Type *PTy = AccessLTy->getPointerTo(addressSpace); 1432 Ptr = Builder.CreateBitCast(Ptr, PTy); 1433 1434 // Extract the piece of the bit-field value to write in this access, limited 1435 // to the values that are part of this access. 1436 llvm::Value *Val = SrcVal; 1437 if (AI.TargetBitOffset) 1438 Val = Builder.CreateLShr(Val, AI.TargetBitOffset); 1439 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(ResSizeInBits, 1440 AI.TargetBitWidth)); 1441 1442 // Extend or truncate to the access size. 1443 if (ResSizeInBits < AI.AccessWidth) 1444 Val = Builder.CreateZExt(Val, AccessLTy); 1445 else if (ResSizeInBits > AI.AccessWidth) 1446 Val = Builder.CreateTrunc(Val, AccessLTy); 1447 1448 // Shift into the position in memory. 1449 if (AI.FieldBitStart) 1450 Val = Builder.CreateShl(Val, AI.FieldBitStart); 1451 1452 // If necessary, load and OR in bits that are outside of the bit-field. 1453 if (AI.TargetBitWidth != AI.AccessWidth) { 1454 llvm::LoadInst *Load = Builder.CreateLoad(Ptr, Dst.isVolatileQualified()); 1455 Load->setAlignment(AccessAlignment.getQuantity()); 1456 1457 // Compute the mask for zeroing the bits that are part of the bit-field. 1458 llvm::APInt InvMask = 1459 ~llvm::APInt::getBitsSet(AI.AccessWidth, AI.FieldBitStart, 1460 AI.FieldBitStart + AI.TargetBitWidth); 1461 1462 // Apply the mask and OR in to the value to write. 1463 Val = Builder.CreateOr(Builder.CreateAnd(Load, InvMask), Val); 1464 } 1465 1466 // Write the value. 1467 llvm::StoreInst *Store = Builder.CreateStore(Val, Ptr, 1468 Dst.isVolatileQualified()); 1469 Store->setAlignment(AccessAlignment.getQuantity()); 1470 } 1471} 1472 1473void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src, 1474 LValue Dst) { 1475 // This access turns into a read/modify/write of the vector. Load the input 1476 // value now. 1477 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getExtVectorAddr(), 1478 Dst.isVolatileQualified()); 1479 Load->setAlignment(Dst.getAlignment().getQuantity()); 1480 llvm::Value *Vec = Load; 1481 const llvm::Constant *Elts = Dst.getExtVectorElts(); 1482 1483 llvm::Value *SrcVal = Src.getScalarVal(); 1484 1485 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) { 1486 unsigned NumSrcElts = VTy->getNumElements(); 1487 unsigned NumDstElts = 1488 cast<llvm::VectorType>(Vec->getType())->getNumElements(); 1489 if (NumDstElts == NumSrcElts) { 1490 // Use shuffle vector is the src and destination are the same number of 1491 // elements and restore the vector mask since it is on the side it will be 1492 // stored. 1493 SmallVector<llvm::Constant*, 4> Mask(NumDstElts); 1494 for (unsigned i = 0; i != NumSrcElts; ++i) 1495 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i); 1496 1497 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1498 Vec = Builder.CreateShuffleVector(SrcVal, 1499 llvm::UndefValue::get(Vec->getType()), 1500 MaskV); 1501 } else if (NumDstElts > NumSrcElts) { 1502 // Extended the source vector to the same length and then shuffle it 1503 // into the destination. 1504 // FIXME: since we're shuffling with undef, can we just use the indices 1505 // into that? This could be simpler. 1506 SmallVector<llvm::Constant*, 4> ExtMask; 1507 for (unsigned i = 0; i != NumSrcElts; ++i) 1508 ExtMask.push_back(Builder.getInt32(i)); 1509 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty)); 1510 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask); 1511 llvm::Value *ExtSrcVal = 1512 Builder.CreateShuffleVector(SrcVal, 1513 llvm::UndefValue::get(SrcVal->getType()), 1514 ExtMaskV); 1515 // build identity 1516 SmallVector<llvm::Constant*, 4> Mask; 1517 for (unsigned i = 0; i != NumDstElts; ++i) 1518 Mask.push_back(Builder.getInt32(i)); 1519 1520 // modify when what gets shuffled in 1521 for (unsigned i = 0; i != NumSrcElts; ++i) 1522 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts); 1523 llvm::Value *MaskV = llvm::ConstantVector::get(Mask); 1524 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV); 1525 } else { 1526 // We should never shorten the vector 1527 llvm_unreachable("unexpected shorten vector length"); 1528 } 1529 } else { 1530 // If the Src is a scalar (not a vector) it must be updating one element. 1531 unsigned InIdx = getAccessedFieldNo(0, Elts); 1532 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx); 1533 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt); 1534 } 1535 1536 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getExtVectorAddr(), 1537 Dst.isVolatileQualified()); 1538 Store->setAlignment(Dst.getAlignment().getQuantity()); 1539} 1540 1541// setObjCGCLValueClass - sets class of he lvalue for the purpose of 1542// generating write-barries API. It is currently a global, ivar, 1543// or neither. 1544static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E, 1545 LValue &LV, 1546 bool IsMemberAccess=false) { 1547 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC) 1548 return; 1549 1550 if (isa<ObjCIvarRefExpr>(E)) { 1551 QualType ExpTy = E->getType(); 1552 if (IsMemberAccess && ExpTy->isPointerType()) { 1553 // If ivar is a structure pointer, assigning to field of 1554 // this struct follows gcc's behavior and makes it a non-ivar 1555 // writer-barrier conservatively. 1556 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType(); 1557 if (ExpTy->isRecordType()) { 1558 LV.setObjCIvar(false); 1559 return; 1560 } 1561 } 1562 LV.setObjCIvar(true); 1563 ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E)); 1564 LV.setBaseIvarExp(Exp->getBase()); 1565 LV.setObjCArray(E->getType()->isArrayType()); 1566 return; 1567 } 1568 1569 if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) { 1570 if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) { 1571 if (VD->hasGlobalStorage()) { 1572 LV.setGlobalObjCRef(true); 1573 LV.setThreadLocalRef(VD->isThreadSpecified()); 1574 } 1575 } 1576 LV.setObjCArray(E->getType()->isArrayType()); 1577 return; 1578 } 1579 1580 if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) { 1581 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 1582 return; 1583 } 1584 1585 if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) { 1586 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 1587 if (LV.isObjCIvar()) { 1588 // If cast is to a structure pointer, follow gcc's behavior and make it 1589 // a non-ivar write-barrier. 1590 QualType ExpTy = E->getType(); 1591 if (ExpTy->isPointerType()) 1592 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType(); 1593 if (ExpTy->isRecordType()) 1594 LV.setObjCIvar(false); 1595 } 1596 return; 1597 } 1598 1599 if (const GenericSelectionExpr *Exp = dyn_cast<GenericSelectionExpr>(E)) { 1600 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV); 1601 return; 1602 } 1603 1604 if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) { 1605 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 1606 return; 1607 } 1608 1609 if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) { 1610 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 1611 return; 1612 } 1613 1614 if (const ObjCBridgedCastExpr *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) { 1615 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 1616 return; 1617 } 1618 1619 if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) { 1620 setObjCGCLValueClass(Ctx, Exp->getBase(), LV); 1621 if (LV.isObjCIvar() && !LV.isObjCArray()) 1622 // Using array syntax to assigning to what an ivar points to is not 1623 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0; 1624 LV.setObjCIvar(false); 1625 else if (LV.isGlobalObjCRef() && !LV.isObjCArray()) 1626 // Using array syntax to assigning to what global points to is not 1627 // same as assigning to the global itself. {id *G;} G[i] = 0; 1628 LV.setGlobalObjCRef(false); 1629 return; 1630 } 1631 1632 if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) { 1633 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true); 1634 // We don't know if member is an 'ivar', but this flag is looked at 1635 // only in the context of LV.isObjCIvar(). 1636 LV.setObjCArray(E->getType()->isArrayType()); 1637 return; 1638 } 1639} 1640 1641static llvm::Value * 1642EmitBitCastOfLValueToProperType(CodeGenFunction &CGF, 1643 llvm::Value *V, llvm::Type *IRType, 1644 StringRef Name = StringRef()) { 1645 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace(); 1646 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name); 1647} 1648 1649static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF, 1650 const Expr *E, const VarDecl *VD) { 1651 assert((VD->hasExternalStorage() || VD->isFileVarDecl()) && 1652 "Var decl must have external storage or be a file var decl!"); 1653 1654 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD); 1655 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType()); 1656 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy); 1657 CharUnits Alignment = CGF.getContext().getDeclAlign(VD); 1658 QualType T = E->getType(); 1659 LValue LV; 1660 if (VD->getType()->isReferenceType()) { 1661 llvm::LoadInst *LI = CGF.Builder.CreateLoad(V); 1662 LI->setAlignment(Alignment.getQuantity()); 1663 V = LI; 1664 LV = CGF.MakeNaturalAlignAddrLValue(V, T); 1665 } else { 1666 LV = CGF.MakeAddrLValue(V, E->getType(), Alignment); 1667 } 1668 setObjCGCLValueClass(CGF.getContext(), E, LV); 1669 return LV; 1670} 1671 1672static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, 1673 const Expr *E, const FunctionDecl *FD) { 1674 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD); 1675 if (!FD->hasPrototype()) { 1676 if (const FunctionProtoType *Proto = 1677 FD->getType()->getAs<FunctionProtoType>()) { 1678 // Ugly case: for a K&R-style definition, the type of the definition 1679 // isn't the same as the type of a use. Correct for this with a 1680 // bitcast. 1681 QualType NoProtoType = 1682 CGF.getContext().getFunctionNoProtoType(Proto->getResultType()); 1683 NoProtoType = CGF.getContext().getPointerType(NoProtoType); 1684 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType)); 1685 } 1686 } 1687 CharUnits Alignment = CGF.getContext().getDeclAlign(FD); 1688 return CGF.MakeAddrLValue(V, E->getType(), Alignment); 1689} 1690 1691LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) { 1692 const NamedDecl *ND = E->getDecl(); 1693 CharUnits Alignment = getContext().getDeclAlign(ND); 1694 QualType T = E->getType(); 1695 1696 // FIXME: We should be able to assert this for FunctionDecls as well! 1697 // FIXME: We should be able to assert this for all DeclRefExprs, not just 1698 // those with a valid source location. 1699 assert((ND->isUsed(false) || !isa<VarDecl>(ND) || 1700 !E->getLocation().isValid()) && 1701 "Should not use decl without marking it used!"); 1702 1703 if (ND->hasAttr<WeakRefAttr>()) { 1704 const ValueDecl *VD = cast<ValueDecl>(ND); 1705 llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD); 1706 return MakeAddrLValue(Aliasee, E->getType(), Alignment); 1707 } 1708 1709 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) { 1710 // Check if this is a global variable. 1711 if (VD->hasExternalStorage() || VD->isFileVarDecl()) 1712 return EmitGlobalVarDeclLValue(*this, E, VD); 1713 1714 bool isBlockVariable = VD->hasAttr<BlocksAttr>(); 1715 1716 bool NonGCable = VD->hasLocalStorage() && 1717 !VD->getType()->isReferenceType() && 1718 !isBlockVariable; 1719 1720 llvm::Value *V = LocalDeclMap[VD]; 1721 if (!V && VD->isStaticLocal()) 1722 V = CGM.getStaticLocalDeclAddress(VD); 1723 1724 // Use special handling for lambdas. 1725 if (!V) { 1726 if (FieldDecl *FD = LambdaCaptureFields.lookup(VD)) { 1727 QualType LambdaTagType = getContext().getTagDeclType(FD->getParent()); 1728 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, 1729 LambdaTagType); 1730 return EmitLValueForField(LambdaLV, FD); 1731 } 1732 1733 assert(isa<BlockDecl>(CurCodeDecl) && E->refersToEnclosingLocal()); 1734 CharUnits alignment = getContext().getDeclAlign(VD); 1735 return MakeAddrLValue(GetAddrOfBlockDecl(VD, isBlockVariable), 1736 E->getType(), alignment); 1737 } 1738 1739 assert(V && "DeclRefExpr not entered in LocalDeclMap?"); 1740 1741 if (isBlockVariable) 1742 V = BuildBlockByrefAddress(V, VD); 1743 1744 LValue LV; 1745 if (VD->getType()->isReferenceType()) { 1746 llvm::LoadInst *LI = Builder.CreateLoad(V); 1747 LI->setAlignment(Alignment.getQuantity()); 1748 V = LI; 1749 LV = MakeNaturalAlignAddrLValue(V, T); 1750 } else { 1751 LV = MakeAddrLValue(V, T, Alignment); 1752 } 1753 1754 if (NonGCable) { 1755 LV.getQuals().removeObjCGCAttr(); 1756 LV.setNonGC(true); 1757 } 1758 setObjCGCLValueClass(getContext(), E, LV); 1759 return LV; 1760 } 1761 1762 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND)) 1763 return EmitFunctionDeclLValue(*this, E, fn); 1764 1765 llvm_unreachable("Unhandled DeclRefExpr"); 1766} 1767 1768LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) { 1769 // __extension__ doesn't affect lvalue-ness. 1770 if (E->getOpcode() == UO_Extension) 1771 return EmitLValue(E->getSubExpr()); 1772 1773 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType()); 1774 switch (E->getOpcode()) { 1775 default: llvm_unreachable("Unknown unary operator lvalue!"); 1776 case UO_Deref: { 1777 QualType T = E->getSubExpr()->getType()->getPointeeType(); 1778 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type"); 1779 1780 LValue LV = MakeNaturalAlignAddrLValue(EmitScalarExpr(E->getSubExpr()), T); 1781 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace()); 1782 1783 // We should not generate __weak write barrier on indirect reference 1784 // of a pointer to object; as in void foo (__weak id *param); *param = 0; 1785 // But, we continue to generate __strong write barrier on indirect write 1786 // into a pointer to object. 1787 if (getContext().getLangOpts().ObjC1 && 1788 getContext().getLangOpts().getGC() != LangOptions::NonGC && 1789 LV.isObjCWeak()) 1790 LV.setNonGC(!E->isOBJCGCCandidate(getContext())); 1791 return LV; 1792 } 1793 case UO_Real: 1794 case UO_Imag: { 1795 LValue LV = EmitLValue(E->getSubExpr()); 1796 assert(LV.isSimple() && "real/imag on non-ordinary l-value"); 1797 llvm::Value *Addr = LV.getAddress(); 1798 1799 // __real is valid on scalars. This is a faster way of testing that. 1800 // __imag can only produce an rvalue on scalars. 1801 if (E->getOpcode() == UO_Real && 1802 !cast<llvm::PointerType>(Addr->getType()) 1803 ->getElementType()->isStructTy()) { 1804 assert(E->getSubExpr()->getType()->isArithmeticType()); 1805 return LV; 1806 } 1807 1808 assert(E->getSubExpr()->getType()->isAnyComplexType()); 1809 1810 unsigned Idx = E->getOpcode() == UO_Imag; 1811 return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(), 1812 Idx, "idx"), 1813 ExprTy); 1814 } 1815 case UO_PreInc: 1816 case UO_PreDec: { 1817 LValue LV = EmitLValue(E->getSubExpr()); 1818 bool isInc = E->getOpcode() == UO_PreInc; 1819 1820 if (E->getType()->isAnyComplexType()) 1821 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/); 1822 else 1823 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/); 1824 return LV; 1825 } 1826 } 1827} 1828 1829LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) { 1830 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E), 1831 E->getType()); 1832} 1833 1834LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) { 1835 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E), 1836 E->getType()); 1837} 1838 1839static llvm::Constant* 1840GetAddrOfConstantWideString(StringRef Str, 1841 const char *GlobalName, 1842 ASTContext &Context, 1843 QualType Ty, SourceLocation Loc, 1844 CodeGenModule &CGM) { 1845 1846 StringLiteral *SL = StringLiteral::Create(Context, 1847 Str, 1848 StringLiteral::Wide, 1849 /*Pascal = */false, 1850 Ty, Loc); 1851 llvm::Constant *C = CGM.GetConstantArrayFromStringLiteral(SL); 1852 llvm::GlobalVariable *GV = 1853 new llvm::GlobalVariable(CGM.getModule(), C->getType(), 1854 !CGM.getLangOpts().WritableStrings, 1855 llvm::GlobalValue::PrivateLinkage, 1856 C, GlobalName); 1857 const unsigned WideAlignment = 1858 Context.getTypeAlignInChars(Ty).getQuantity(); 1859 GV->setAlignment(WideAlignment); 1860 return GV; 1861} 1862 1863static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 1864 SmallString<32>& Target) { 1865 Target.resize(CharByteWidth * (Source.size() + 1)); 1866 char *ResultPtr = &Target[0]; 1867 const UTF8 *ErrorPtr; 1868 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 1869 (void)success; 1870 assert(success); 1871 Target.resize(ResultPtr - &Target[0]); 1872} 1873 1874LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) { 1875 switch (E->getIdentType()) { 1876 default: 1877 return EmitUnsupportedLValue(E, "predefined expression"); 1878 1879 case PredefinedExpr::Func: 1880 case PredefinedExpr::Function: 1881 case PredefinedExpr::LFunction: 1882 case PredefinedExpr::PrettyFunction: { 1883 unsigned IdentType = E->getIdentType(); 1884 std::string GlobalVarName; 1885 1886 switch (IdentType) { 1887 default: llvm_unreachable("Invalid type"); 1888 case PredefinedExpr::Func: 1889 GlobalVarName = "__func__."; 1890 break; 1891 case PredefinedExpr::Function: 1892 GlobalVarName = "__FUNCTION__."; 1893 break; 1894 case PredefinedExpr::LFunction: 1895 GlobalVarName = "L__FUNCTION__."; 1896 break; 1897 case PredefinedExpr::PrettyFunction: 1898 GlobalVarName = "__PRETTY_FUNCTION__."; 1899 break; 1900 } 1901 1902 StringRef FnName = CurFn->getName(); 1903 if (FnName.startswith("\01")) 1904 FnName = FnName.substr(1); 1905 GlobalVarName += FnName; 1906 1907 const Decl *CurDecl = CurCodeDecl; 1908 if (CurDecl == 0) 1909 CurDecl = getContext().getTranslationUnitDecl(); 1910 1911 std::string FunctionName = 1912 (isa<BlockDecl>(CurDecl) 1913 ? FnName.str() 1914 : PredefinedExpr::ComputeName((PredefinedExpr::IdentType)IdentType, 1915 CurDecl)); 1916 1917 const Type* ElemType = E->getType()->getArrayElementTypeNoTypeQual(); 1918 llvm::Constant *C; 1919 if (ElemType->isWideCharType()) { 1920 SmallString<32> RawChars; 1921 ConvertUTF8ToWideString( 1922 getContext().getTypeSizeInChars(ElemType).getQuantity(), 1923 FunctionName, RawChars); 1924 C = GetAddrOfConstantWideString(RawChars, 1925 GlobalVarName.c_str(), 1926 getContext(), 1927 E->getType(), 1928 E->getLocation(), 1929 CGM); 1930 } else { 1931 C = CGM.GetAddrOfConstantCString(FunctionName, 1932 GlobalVarName.c_str(), 1933 1); 1934 } 1935 return MakeAddrLValue(C, E->getType()); 1936 } 1937 } 1938} 1939 1940/// Emit a type description suitable for use by a runtime sanitizer library. The 1941/// format of a type descriptor is 1942/// 1943/// \code 1944/// { i16 TypeKind, i16 TypeInfo } 1945/// \endcode 1946/// 1947/// followed by an array of i8 containing the type name. TypeKind is 0 for an 1948/// integer, 1 for a floating point value, and -1 for anything else. 1949llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) { 1950 // FIXME: Only emit each type's descriptor once. 1951 uint16_t TypeKind = -1; 1952 uint16_t TypeInfo = 0; 1953 1954 if (T->isIntegerType()) { 1955 TypeKind = 0; 1956 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) | 1957 T->isSignedIntegerType(); 1958 } else if (T->isFloatingType()) { 1959 TypeKind = 1; 1960 TypeInfo = getContext().getTypeSize(T); 1961 } 1962 1963 // Format the type name as if for a diagnostic, including quotes and 1964 // optionally an 'aka'. 1965 llvm::SmallString<32> Buffer; 1966 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype, 1967 (intptr_t)T.getAsOpaquePtr(), 1968 0, 0, 0, 0, 0, 0, Buffer, 1969 ArrayRef<intptr_t>()); 1970 1971 llvm::Constant *Components[] = { 1972 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo), 1973 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer) 1974 }; 1975 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components); 1976 1977 llvm::GlobalVariable *GV = 1978 new llvm::GlobalVariable(CGM.getModule(), Descriptor->getType(), 1979 /*isConstant=*/true, 1980 llvm::GlobalVariable::PrivateLinkage, 1981 Descriptor); 1982 GV->setUnnamedAddr(true); 1983 return GV; 1984} 1985 1986llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) { 1987 llvm::Type *TargetTy = IntPtrTy; 1988 1989 // Integers which fit in intptr_t are zero-extended and passed directly. 1990 if (V->getType()->isIntegerTy() && 1991 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth()) 1992 return Builder.CreateZExt(V, TargetTy); 1993 1994 // Pointers are passed directly, everything else is passed by address. 1995 if (!V->getType()->isPointerTy()) { 1996 llvm::Value *Ptr = Builder.CreateAlloca(V->getType()); 1997 Builder.CreateStore(V, Ptr); 1998 V = Ptr; 1999 } 2000 return Builder.CreatePtrToInt(V, TargetTy); 2001} 2002 2003/// \brief Emit a representation of a SourceLocation for passing to a handler 2004/// in a sanitizer runtime library. The format for this data is: 2005/// \code 2006/// struct SourceLocation { 2007/// const char *Filename; 2008/// int32_t Line, Column; 2009/// }; 2010/// \endcode 2011/// For an invalid SourceLocation, the Filename pointer is null. 2012llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) { 2013 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc); 2014 2015 llvm::Constant *Data[] = { 2016 // FIXME: Only emit each file name once. 2017 PLoc.isValid() ? cast<llvm::Constant>( 2018 Builder.CreateGlobalStringPtr(PLoc.getFilename())) 2019 : llvm::Constant::getNullValue(Int8PtrTy), 2020 Builder.getInt32(PLoc.getLine()), 2021 Builder.getInt32(PLoc.getColumn()) 2022 }; 2023 2024 return llvm::ConstantStruct::getAnon(Data); 2025} 2026 2027void CodeGenFunction::EmitCheck(llvm::Value *Checked, StringRef CheckName, 2028 llvm::ArrayRef<llvm::Constant *> StaticArgs, 2029 llvm::ArrayRef<llvm::Value *> DynamicArgs) { 2030 llvm::BasicBlock *Cont = createBasicBlock("cont"); 2031 2032 // If -fcatch-undefined-behavior is not enabled, just emit a trap. This 2033 // happens when using -ftrapv. 2034 // FIXME: Should -ftrapv require the ubsan runtime library? 2035 if (!CatchUndefined) { 2036 // If we're optimizing, collapse all calls to trap down to just one per 2037 // function to save on code size. 2038 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) { 2039 TrapBB = createBasicBlock("trap"); 2040 Builder.CreateCondBr(Checked, Cont, TrapBB); 2041 EmitBlock(TrapBB); 2042 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap); 2043 llvm::CallInst *TrapCall = Builder.CreateCall(F); 2044 TrapCall->setDoesNotReturn(); 2045 TrapCall->setDoesNotThrow(); 2046 Builder.CreateUnreachable(); 2047 } else { 2048 Builder.CreateCondBr(Checked, Cont, TrapBB); 2049 } 2050 2051 EmitBlock(Cont); 2052 return; 2053 } 2054 2055 llvm::BasicBlock *Handler = createBasicBlock("handler." + CheckName); 2056 Builder.CreateCondBr(Checked, Cont, Handler); 2057 EmitBlock(Handler); 2058 2059 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs); 2060 llvm::GlobalValue *InfoPtr = 2061 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), true, 2062 llvm::GlobalVariable::PrivateLinkage, Info); 2063 InfoPtr->setUnnamedAddr(true); 2064 2065 llvm::SmallVector<llvm::Value *, 4> Args; 2066 llvm::SmallVector<llvm::Type *, 4> ArgTypes; 2067 Args.reserve(DynamicArgs.size() + 1); 2068 ArgTypes.reserve(DynamicArgs.size() + 1); 2069 2070 // Handler functions take an i8* pointing to the (handler-specific) static 2071 // information block, followed by a sequence of intptr_t arguments 2072 // representing operand values. 2073 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy)); 2074 ArgTypes.push_back(Int8PtrTy); 2075 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) { 2076 Args.push_back(EmitCheckValue(DynamicArgs[i])); 2077 ArgTypes.push_back(IntPtrTy); 2078 } 2079 2080 llvm::FunctionType *FnType = 2081 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false); 2082 llvm::Value *Fn = CGM.CreateRuntimeFunction(FnType, 2083 ("__ubsan_handle_" + CheckName).str(), 2084 llvm::Attribute::NoReturn | 2085 llvm::Attribute::NoUnwind | 2086 llvm::Attribute::UWTable); 2087 llvm::CallInst *HandlerCall = Builder.CreateCall(Fn, Args); 2088 HandlerCall->setDoesNotReturn(); 2089 HandlerCall->setDoesNotThrow(); 2090 Builder.CreateUnreachable(); 2091 2092 EmitBlock(Cont); 2093} 2094 2095/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an 2096/// array to pointer, return the array subexpression. 2097static const Expr *isSimpleArrayDecayOperand(const Expr *E) { 2098 // If this isn't just an array->pointer decay, bail out. 2099 const CastExpr *CE = dyn_cast<CastExpr>(E); 2100 if (CE == 0 || CE->getCastKind() != CK_ArrayToPointerDecay) 2101 return 0; 2102 2103 // If this is a decay from variable width array, bail out. 2104 const Expr *SubExpr = CE->getSubExpr(); 2105 if (SubExpr->getType()->isVariableArrayType()) 2106 return 0; 2107 2108 return SubExpr; 2109} 2110 2111LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) { 2112 // The index must always be an integer, which is not an aggregate. Emit it. 2113 llvm::Value *Idx = EmitScalarExpr(E->getIdx()); 2114 QualType IdxTy = E->getIdx()->getType(); 2115 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType(); 2116 2117 // If the base is a vector type, then we are forming a vector element lvalue 2118 // with this subscript. 2119 if (E->getBase()->getType()->isVectorType()) { 2120 // Emit the vector as an lvalue to get its address. 2121 LValue LHS = EmitLValue(E->getBase()); 2122 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!"); 2123 Idx = Builder.CreateIntCast(Idx, Int32Ty, IdxSigned, "vidx"); 2124 return LValue::MakeVectorElt(LHS.getAddress(), Idx, 2125 E->getBase()->getType(), LHS.getAlignment()); 2126 } 2127 2128 // Extend or truncate the index type to 32 or 64-bits. 2129 if (Idx->getType() != IntPtrTy) 2130 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom"); 2131 2132 // We know that the pointer points to a type of the correct size, unless the 2133 // size is a VLA or Objective-C interface. 2134 llvm::Value *Address = 0; 2135 CharUnits ArrayAlignment; 2136 if (const VariableArrayType *vla = 2137 getContext().getAsVariableArrayType(E->getType())) { 2138 // The base must be a pointer, which is not an aggregate. Emit 2139 // it. It needs to be emitted first in case it's what captures 2140 // the VLA bounds. 2141 Address = EmitScalarExpr(E->getBase()); 2142 2143 // The element count here is the total number of non-VLA elements. 2144 llvm::Value *numElements = getVLASize(vla).first; 2145 2146 // Effectively, the multiply by the VLA size is part of the GEP. 2147 // GEP indexes are signed, and scaling an index isn't permitted to 2148 // signed-overflow, so we use the same semantics for our explicit 2149 // multiply. We suppress this if overflow is not undefined behavior. 2150 if (getLangOpts().isSignedOverflowDefined()) { 2151 Idx = Builder.CreateMul(Idx, numElements); 2152 Address = Builder.CreateGEP(Address, Idx, "arrayidx"); 2153 } else { 2154 Idx = Builder.CreateNSWMul(Idx, numElements); 2155 Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx"); 2156 } 2157 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){ 2158 // Indexing over an interface, as in "NSString *P; P[4];" 2159 llvm::Value *InterfaceSize = 2160 llvm::ConstantInt::get(Idx->getType(), 2161 getContext().getTypeSizeInChars(OIT).getQuantity()); 2162 2163 Idx = Builder.CreateMul(Idx, InterfaceSize); 2164 2165 // The base must be a pointer, which is not an aggregate. Emit it. 2166 llvm::Value *Base = EmitScalarExpr(E->getBase()); 2167 Address = EmitCastToVoidPtr(Base); 2168 Address = Builder.CreateGEP(Address, Idx, "arrayidx"); 2169 Address = Builder.CreateBitCast(Address, Base->getType()); 2170 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) { 2171 // If this is A[i] where A is an array, the frontend will have decayed the 2172 // base to be a ArrayToPointerDecay implicit cast. While correct, it is 2173 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a 2174 // "gep x, i" here. Emit one "gep A, 0, i". 2175 assert(Array->getType()->isArrayType() && 2176 "Array to pointer decay must have array source type!"); 2177 LValue ArrayLV = EmitLValue(Array); 2178 llvm::Value *ArrayPtr = ArrayLV.getAddress(); 2179 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0); 2180 llvm::Value *Args[] = { Zero, Idx }; 2181 2182 // Propagate the alignment from the array itself to the result. 2183 ArrayAlignment = ArrayLV.getAlignment(); 2184 2185 if (getContext().getLangOpts().isSignedOverflowDefined()) 2186 Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx"); 2187 else 2188 Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx"); 2189 } else { 2190 // The base must be a pointer, which is not an aggregate. Emit it. 2191 llvm::Value *Base = EmitScalarExpr(E->getBase()); 2192 if (getContext().getLangOpts().isSignedOverflowDefined()) 2193 Address = Builder.CreateGEP(Base, Idx, "arrayidx"); 2194 else 2195 Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx"); 2196 } 2197 2198 QualType T = E->getBase()->getType()->getPointeeType(); 2199 assert(!T.isNull() && 2200 "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type"); 2201 2202 2203 // Limit the alignment to that of the result type. 2204 LValue LV; 2205 if (!ArrayAlignment.isZero()) { 2206 CharUnits Align = getContext().getTypeAlignInChars(T); 2207 ArrayAlignment = std::min(Align, ArrayAlignment); 2208 LV = MakeAddrLValue(Address, T, ArrayAlignment); 2209 } else { 2210 LV = MakeNaturalAlignAddrLValue(Address, T); 2211 } 2212 2213 LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace()); 2214 2215 if (getContext().getLangOpts().ObjC1 && 2216 getContext().getLangOpts().getGC() != LangOptions::NonGC) { 2217 LV.setNonGC(!E->isOBJCGCCandidate(getContext())); 2218 setObjCGCLValueClass(getContext(), E, LV); 2219 } 2220 return LV; 2221} 2222 2223static 2224llvm::Constant *GenerateConstantVector(CGBuilderTy &Builder, 2225 SmallVector<unsigned, 4> &Elts) { 2226 SmallVector<llvm::Constant*, 4> CElts; 2227 for (unsigned i = 0, e = Elts.size(); i != e; ++i) 2228 CElts.push_back(Builder.getInt32(Elts[i])); 2229 2230 return llvm::ConstantVector::get(CElts); 2231} 2232 2233LValue CodeGenFunction:: 2234EmitExtVectorElementExpr(const ExtVectorElementExpr *E) { 2235 // Emit the base vector as an l-value. 2236 LValue Base; 2237 2238 // ExtVectorElementExpr's base can either be a vector or pointer to vector. 2239 if (E->isArrow()) { 2240 // If it is a pointer to a vector, emit the address and form an lvalue with 2241 // it. 2242 llvm::Value *Ptr = EmitScalarExpr(E->getBase()); 2243 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>(); 2244 Base = MakeAddrLValue(Ptr, PT->getPointeeType()); 2245 Base.getQuals().removeObjCGCAttr(); 2246 } else if (E->getBase()->isGLValue()) { 2247 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x), 2248 // emit the base as an lvalue. 2249 assert(E->getBase()->getType()->isVectorType()); 2250 Base = EmitLValue(E->getBase()); 2251 } else { 2252 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such. 2253 assert(E->getBase()->getType()->isVectorType() && 2254 "Result must be a vector"); 2255 llvm::Value *Vec = EmitScalarExpr(E->getBase()); 2256 2257 // Store the vector to memory (because LValue wants an address). 2258 llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType()); 2259 Builder.CreateStore(Vec, VecMem); 2260 Base = MakeAddrLValue(VecMem, E->getBase()->getType()); 2261 } 2262 2263 QualType type = 2264 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers()); 2265 2266 // Encode the element access list into a vector of unsigned indices. 2267 SmallVector<unsigned, 4> Indices; 2268 E->getEncodedElementAccess(Indices); 2269 2270 if (Base.isSimple()) { 2271 llvm::Constant *CV = GenerateConstantVector(Builder, Indices); 2272 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type, 2273 Base.getAlignment()); 2274 } 2275 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!"); 2276 2277 llvm::Constant *BaseElts = Base.getExtVectorElts(); 2278 SmallVector<llvm::Constant *, 4> CElts; 2279 2280 for (unsigned i = 0, e = Indices.size(); i != e; ++i) 2281 CElts.push_back(BaseElts->getAggregateElement(Indices[i])); 2282 llvm::Constant *CV = llvm::ConstantVector::get(CElts); 2283 return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type, 2284 Base.getAlignment()); 2285} 2286 2287LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) { 2288 Expr *BaseExpr = E->getBase(); 2289 2290 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 2291 LValue BaseLV; 2292 if (E->isArrow()) { 2293 llvm::Value *Ptr = EmitScalarExpr(BaseExpr); 2294 QualType PtrTy = BaseExpr->getType()->getPointeeType(); 2295 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Ptr, PtrTy); 2296 BaseLV = MakeNaturalAlignAddrLValue(Ptr, PtrTy); 2297 } else 2298 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess); 2299 2300 NamedDecl *ND = E->getMemberDecl(); 2301 if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) { 2302 LValue LV = EmitLValueForField(BaseLV, Field); 2303 setObjCGCLValueClass(getContext(), E, LV); 2304 return LV; 2305 } 2306 2307 if (VarDecl *VD = dyn_cast<VarDecl>(ND)) 2308 return EmitGlobalVarDeclLValue(*this, E, VD); 2309 2310 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) 2311 return EmitFunctionDeclLValue(*this, E, FD); 2312 2313 llvm_unreachable("Unhandled member declaration!"); 2314} 2315 2316LValue CodeGenFunction::EmitLValueForField(LValue base, 2317 const FieldDecl *field) { 2318 if (field->isBitField()) { 2319 const CGRecordLayout &RL = 2320 CGM.getTypes().getCGRecordLayout(field->getParent()); 2321 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field); 2322 QualType fieldType = 2323 field->getType().withCVRQualifiers(base.getVRQualifiers()); 2324 return LValue::MakeBitfield(base.getAddress(), Info, fieldType, 2325 base.getAlignment()); 2326 } 2327 2328 const RecordDecl *rec = field->getParent(); 2329 QualType type = field->getType(); 2330 CharUnits alignment = getContext().getDeclAlign(field); 2331 2332 // FIXME: It should be impossible to have an LValue without alignment for a 2333 // complete type. 2334 if (!base.getAlignment().isZero()) 2335 alignment = std::min(alignment, base.getAlignment()); 2336 2337 bool mayAlias = rec->hasAttr<MayAliasAttr>(); 2338 2339 llvm::Value *addr = base.getAddress(); 2340 unsigned cvr = base.getVRQualifiers(); 2341 if (rec->isUnion()) { 2342 // For unions, there is no pointer adjustment. 2343 assert(!type->isReferenceType() && "union has reference member"); 2344 } else { 2345 // For structs, we GEP to the field that the record layout suggests. 2346 unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field); 2347 addr = Builder.CreateStructGEP(addr, idx, field->getName()); 2348 2349 // If this is a reference field, load the reference right now. 2350 if (const ReferenceType *refType = type->getAs<ReferenceType>()) { 2351 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref"); 2352 if (cvr & Qualifiers::Volatile) load->setVolatile(true); 2353 load->setAlignment(alignment.getQuantity()); 2354 2355 if (CGM.shouldUseTBAA()) { 2356 llvm::MDNode *tbaa; 2357 if (mayAlias) 2358 tbaa = CGM.getTBAAInfo(getContext().CharTy); 2359 else 2360 tbaa = CGM.getTBAAInfo(type); 2361 CGM.DecorateInstruction(load, tbaa); 2362 } 2363 2364 addr = load; 2365 mayAlias = false; 2366 type = refType->getPointeeType(); 2367 if (type->isIncompleteType()) 2368 alignment = CharUnits(); 2369 else 2370 alignment = getContext().getTypeAlignInChars(type); 2371 cvr = 0; // qualifiers don't recursively apply to referencee 2372 } 2373 } 2374 2375 // Make sure that the address is pointing to the right type. This is critical 2376 // for both unions and structs. A union needs a bitcast, a struct element 2377 // will need a bitcast if the LLVM type laid out doesn't match the desired 2378 // type. 2379 addr = EmitBitCastOfLValueToProperType(*this, addr, 2380 CGM.getTypes().ConvertTypeForMem(type), 2381 field->getName()); 2382 2383 if (field->hasAttr<AnnotateAttr>()) 2384 addr = EmitFieldAnnotations(field, addr); 2385 2386 LValue LV = MakeAddrLValue(addr, type, alignment); 2387 LV.getQuals().addCVRQualifiers(cvr); 2388 2389 // __weak attribute on a field is ignored. 2390 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak) 2391 LV.getQuals().removeObjCGCAttr(); 2392 2393 // Fields of may_alias structs act like 'char' for TBAA purposes. 2394 // FIXME: this should get propagated down through anonymous structs 2395 // and unions. 2396 if (mayAlias && LV.getTBAAInfo()) 2397 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy)); 2398 2399 return LV; 2400} 2401 2402LValue 2403CodeGenFunction::EmitLValueForFieldInitialization(LValue Base, 2404 const FieldDecl *Field) { 2405 QualType FieldType = Field->getType(); 2406 2407 if (!FieldType->isReferenceType()) 2408 return EmitLValueForField(Base, Field); 2409 2410 const CGRecordLayout &RL = 2411 CGM.getTypes().getCGRecordLayout(Field->getParent()); 2412 unsigned idx = RL.getLLVMFieldNo(Field); 2413 llvm::Value *V = Builder.CreateStructGEP(Base.getAddress(), idx); 2414 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs"); 2415 2416 // Make sure that the address is pointing to the right type. This is critical 2417 // for both unions and structs. A union needs a bitcast, a struct element 2418 // will need a bitcast if the LLVM type laid out doesn't match the desired 2419 // type. 2420 llvm::Type *llvmType = ConvertTypeForMem(FieldType); 2421 V = EmitBitCastOfLValueToProperType(*this, V, llvmType, Field->getName()); 2422 2423 CharUnits Alignment = getContext().getDeclAlign(Field); 2424 2425 // FIXME: It should be impossible to have an LValue without alignment for a 2426 // complete type. 2427 if (!Base.getAlignment().isZero()) 2428 Alignment = std::min(Alignment, Base.getAlignment()); 2429 2430 return MakeAddrLValue(V, FieldType, Alignment); 2431} 2432 2433LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){ 2434 if (E->isFileScope()) { 2435 llvm::Value *GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E); 2436 return MakeAddrLValue(GlobalPtr, E->getType()); 2437 } 2438 if (E->getType()->isVariablyModifiedType()) 2439 // make sure to emit the VLA size. 2440 EmitVariablyModifiedType(E->getType()); 2441 2442 llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral"); 2443 const Expr *InitExpr = E->getInitializer(); 2444 LValue Result = MakeAddrLValue(DeclPtr, E->getType()); 2445 2446 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(), 2447 /*Init*/ true); 2448 2449 return Result; 2450} 2451 2452LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) { 2453 if (!E->isGLValue()) 2454 // Initializing an aggregate temporary in C++11: T{...}. 2455 return EmitAggExprToLValue(E); 2456 2457 // An lvalue initializer list must be initializing a reference. 2458 assert(E->getNumInits() == 1 && "reference init with multiple values"); 2459 return EmitLValue(E->getInit(0)); 2460} 2461 2462LValue CodeGenFunction:: 2463EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) { 2464 if (!expr->isGLValue()) { 2465 // ?: here should be an aggregate. 2466 assert((hasAggregateLLVMType(expr->getType()) && 2467 !expr->getType()->isAnyComplexType()) && 2468 "Unexpected conditional operator!"); 2469 return EmitAggExprToLValue(expr); 2470 } 2471 2472 OpaqueValueMapping binding(*this, expr); 2473 2474 const Expr *condExpr = expr->getCond(); 2475 bool CondExprBool; 2476 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) { 2477 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr(); 2478 if (!CondExprBool) std::swap(live, dead); 2479 2480 if (!ContainsLabel(dead)) 2481 return EmitLValue(live); 2482 } 2483 2484 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true"); 2485 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false"); 2486 llvm::BasicBlock *contBlock = createBasicBlock("cond.end"); 2487 2488 ConditionalEvaluation eval(*this); 2489 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock); 2490 2491 // Any temporaries created here are conditional. 2492 EmitBlock(lhsBlock); 2493 eval.begin(*this); 2494 LValue lhs = EmitLValue(expr->getTrueExpr()); 2495 eval.end(*this); 2496 2497 if (!lhs.isSimple()) 2498 return EmitUnsupportedLValue(expr, "conditional operator"); 2499 2500 lhsBlock = Builder.GetInsertBlock(); 2501 Builder.CreateBr(contBlock); 2502 2503 // Any temporaries created here are conditional. 2504 EmitBlock(rhsBlock); 2505 eval.begin(*this); 2506 LValue rhs = EmitLValue(expr->getFalseExpr()); 2507 eval.end(*this); 2508 if (!rhs.isSimple()) 2509 return EmitUnsupportedLValue(expr, "conditional operator"); 2510 rhsBlock = Builder.GetInsertBlock(); 2511 2512 EmitBlock(contBlock); 2513 2514 llvm::PHINode *phi = Builder.CreatePHI(lhs.getAddress()->getType(), 2, 2515 "cond-lvalue"); 2516 phi->addIncoming(lhs.getAddress(), lhsBlock); 2517 phi->addIncoming(rhs.getAddress(), rhsBlock); 2518 return MakeAddrLValue(phi, expr->getType()); 2519} 2520 2521/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference 2522/// type. If the cast is to a reference, we can have the usual lvalue result, 2523/// otherwise if a cast is needed by the code generator in an lvalue context, 2524/// then it must mean that we need the address of an aggregate in order to 2525/// access one of its members. This can happen for all the reasons that casts 2526/// are permitted with aggregate result, including noop aggregate casts, and 2527/// cast from scalar to union. 2528LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) { 2529 switch (E->getCastKind()) { 2530 case CK_ToVoid: 2531 return EmitUnsupportedLValue(E, "unexpected cast lvalue"); 2532 2533 case CK_Dependent: 2534 llvm_unreachable("dependent cast kind in IR gen!"); 2535 2536 case CK_BuiltinFnToFnPtr: 2537 llvm_unreachable("builtin functions are handled elsewhere"); 2538 2539 // These two casts are currently treated as no-ops, although they could 2540 // potentially be real operations depending on the target's ABI. 2541 case CK_NonAtomicToAtomic: 2542 case CK_AtomicToNonAtomic: 2543 2544 case CK_NoOp: 2545 case CK_LValueToRValue: 2546 if (!E->getSubExpr()->Classify(getContext()).isPRValue() 2547 || E->getType()->isRecordType()) 2548 return EmitLValue(E->getSubExpr()); 2549 // Fall through to synthesize a temporary. 2550 2551 case CK_BitCast: 2552 case CK_ArrayToPointerDecay: 2553 case CK_FunctionToPointerDecay: 2554 case CK_NullToMemberPointer: 2555 case CK_NullToPointer: 2556 case CK_IntegralToPointer: 2557 case CK_PointerToIntegral: 2558 case CK_PointerToBoolean: 2559 case CK_VectorSplat: 2560 case CK_IntegralCast: 2561 case CK_IntegralToBoolean: 2562 case CK_IntegralToFloating: 2563 case CK_FloatingToIntegral: 2564 case CK_FloatingToBoolean: 2565 case CK_FloatingCast: 2566 case CK_FloatingRealToComplex: 2567 case CK_FloatingComplexToReal: 2568 case CK_FloatingComplexToBoolean: 2569 case CK_FloatingComplexCast: 2570 case CK_FloatingComplexToIntegralComplex: 2571 case CK_IntegralRealToComplex: 2572 case CK_IntegralComplexToReal: 2573 case CK_IntegralComplexToBoolean: 2574 case CK_IntegralComplexCast: 2575 case CK_IntegralComplexToFloatingComplex: 2576 case CK_DerivedToBaseMemberPointer: 2577 case CK_BaseToDerivedMemberPointer: 2578 case CK_MemberPointerToBoolean: 2579 case CK_ReinterpretMemberPointer: 2580 case CK_AnyPointerToBlockPointerCast: 2581 case CK_ARCProduceObject: 2582 case CK_ARCConsumeObject: 2583 case CK_ARCReclaimReturnedObject: 2584 case CK_ARCExtendBlockObject: 2585 case CK_CopyAndAutoreleaseBlockObject: { 2586 // These casts only produce lvalues when we're binding a reference to a 2587 // temporary realized from a (converted) pure rvalue. Emit the expression 2588 // as a value, copy it into a temporary, and return an lvalue referring to 2589 // that temporary. 2590 llvm::Value *V = CreateMemTemp(E->getType(), "ref.temp"); 2591 EmitAnyExprToMem(E, V, E->getType().getQualifiers(), false); 2592 return MakeAddrLValue(V, E->getType()); 2593 } 2594 2595 case CK_Dynamic: { 2596 LValue LV = EmitLValue(E->getSubExpr()); 2597 llvm::Value *V = LV.getAddress(); 2598 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E); 2599 return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType()); 2600 } 2601 2602 case CK_ConstructorConversion: 2603 case CK_UserDefinedConversion: 2604 case CK_CPointerToObjCPointerCast: 2605 case CK_BlockPointerToObjCPointerCast: 2606 return EmitLValue(E->getSubExpr()); 2607 2608 case CK_UncheckedDerivedToBase: 2609 case CK_DerivedToBase: { 2610 const RecordType *DerivedClassTy = 2611 E->getSubExpr()->getType()->getAs<RecordType>(); 2612 CXXRecordDecl *DerivedClassDecl = 2613 cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 2614 2615 LValue LV = EmitLValue(E->getSubExpr()); 2616 llvm::Value *This = LV.getAddress(); 2617 2618 // Perform the derived-to-base conversion 2619 llvm::Value *Base = 2620 GetAddressOfBaseClass(This, DerivedClassDecl, 2621 E->path_begin(), E->path_end(), 2622 /*NullCheckValue=*/false); 2623 2624 return MakeAddrLValue(Base, E->getType()); 2625 } 2626 case CK_ToUnion: 2627 return EmitAggExprToLValue(E); 2628 case CK_BaseToDerived: { 2629 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>(); 2630 CXXRecordDecl *DerivedClassDecl = 2631 cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 2632 2633 LValue LV = EmitLValue(E->getSubExpr()); 2634 2635 // Perform the base-to-derived conversion 2636 llvm::Value *Derived = 2637 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl, 2638 E->path_begin(), E->path_end(), 2639 /*NullCheckValue=*/false); 2640 2641 return MakeAddrLValue(Derived, E->getType()); 2642 } 2643 case CK_LValueBitCast: { 2644 // This must be a reinterpret_cast (or c-style equivalent). 2645 const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E); 2646 2647 LValue LV = EmitLValue(E->getSubExpr()); 2648 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(), 2649 ConvertType(CE->getTypeAsWritten())); 2650 return MakeAddrLValue(V, E->getType()); 2651 } 2652 case CK_ObjCObjectLValueCast: { 2653 LValue LV = EmitLValue(E->getSubExpr()); 2654 QualType ToType = getContext().getLValueReferenceType(E->getType()); 2655 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(), 2656 ConvertType(ToType)); 2657 return MakeAddrLValue(V, E->getType()); 2658 } 2659 } 2660 2661 llvm_unreachable("Unhandled lvalue cast kind?"); 2662} 2663 2664LValue CodeGenFunction::EmitNullInitializationLValue( 2665 const CXXScalarValueInitExpr *E) { 2666 QualType Ty = E->getType(); 2667 LValue LV = MakeAddrLValue(CreateMemTemp(Ty), Ty); 2668 EmitNullInitialization(LV.getAddress(), Ty); 2669 return LV; 2670} 2671 2672LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) { 2673 assert(OpaqueValueMappingData::shouldBindAsLValue(e)); 2674 return getOpaqueLValueMapping(e); 2675} 2676 2677LValue CodeGenFunction::EmitMaterializeTemporaryExpr( 2678 const MaterializeTemporaryExpr *E) { 2679 RValue RV = EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0); 2680 return MakeAddrLValue(RV.getScalarVal(), E->getType()); 2681} 2682 2683RValue CodeGenFunction::EmitRValueForField(LValue LV, 2684 const FieldDecl *FD) { 2685 QualType FT = FD->getType(); 2686 LValue FieldLV = EmitLValueForField(LV, FD); 2687 if (FT->isAnyComplexType()) 2688 return RValue::getComplex( 2689 LoadComplexFromAddr(FieldLV.getAddress(), 2690 FieldLV.isVolatileQualified())); 2691 else if (CodeGenFunction::hasAggregateLLVMType(FT)) 2692 return FieldLV.asAggregateRValue(); 2693 2694 return EmitLoadOfLValue(FieldLV); 2695} 2696 2697//===--------------------------------------------------------------------===// 2698// Expression Emission 2699//===--------------------------------------------------------------------===// 2700 2701RValue CodeGenFunction::EmitCallExpr(const CallExpr *E, 2702 ReturnValueSlot ReturnValue) { 2703 if (CGDebugInfo *DI = getDebugInfo()) 2704 DI->EmitLocation(Builder, E->getLocStart()); 2705 2706 // Builtins never have block type. 2707 if (E->getCallee()->getType()->isBlockPointerType()) 2708 return EmitBlockCallExpr(E, ReturnValue); 2709 2710 if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E)) 2711 return EmitCXXMemberCallExpr(CE, ReturnValue); 2712 2713 if (const CUDAKernelCallExpr *CE = dyn_cast<CUDAKernelCallExpr>(E)) 2714 return EmitCUDAKernelCallExpr(CE, ReturnValue); 2715 2716 const Decl *TargetDecl = E->getCalleeDecl(); 2717 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) { 2718 if (unsigned builtinID = FD->getBuiltinID()) 2719 return EmitBuiltinExpr(FD, builtinID, E); 2720 } 2721 2722 if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E)) 2723 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl)) 2724 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue); 2725 2726 if (const CXXPseudoDestructorExpr *PseudoDtor 2727 = dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) { 2728 QualType DestroyedType = PseudoDtor->getDestroyedType(); 2729 if (getContext().getLangOpts().ObjCAutoRefCount && 2730 DestroyedType->isObjCLifetimeType() && 2731 (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong || 2732 DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) { 2733 // Automatic Reference Counting: 2734 // If the pseudo-expression names a retainable object with weak or 2735 // strong lifetime, the object shall be released. 2736 Expr *BaseExpr = PseudoDtor->getBase(); 2737 llvm::Value *BaseValue = NULL; 2738 Qualifiers BaseQuals; 2739 2740 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 2741 if (PseudoDtor->isArrow()) { 2742 BaseValue = EmitScalarExpr(BaseExpr); 2743 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>(); 2744 BaseQuals = PTy->getPointeeType().getQualifiers(); 2745 } else { 2746 LValue BaseLV = EmitLValue(BaseExpr); 2747 BaseValue = BaseLV.getAddress(); 2748 QualType BaseTy = BaseExpr->getType(); 2749 BaseQuals = BaseTy.getQualifiers(); 2750 } 2751 2752 switch (PseudoDtor->getDestroyedType().getObjCLifetime()) { 2753 case Qualifiers::OCL_None: 2754 case Qualifiers::OCL_ExplicitNone: 2755 case Qualifiers::OCL_Autoreleasing: 2756 break; 2757 2758 case Qualifiers::OCL_Strong: 2759 EmitARCRelease(Builder.CreateLoad(BaseValue, 2760 PseudoDtor->getDestroyedType().isVolatileQualified()), 2761 /*precise*/ true); 2762 break; 2763 2764 case Qualifiers::OCL_Weak: 2765 EmitARCDestroyWeak(BaseValue); 2766 break; 2767 } 2768 } else { 2769 // C++ [expr.pseudo]p1: 2770 // The result shall only be used as the operand for the function call 2771 // operator (), and the result of such a call has type void. The only 2772 // effect is the evaluation of the postfix-expression before the dot or 2773 // arrow. 2774 EmitScalarExpr(E->getCallee()); 2775 } 2776 2777 return RValue::get(0); 2778 } 2779 2780 llvm::Value *Callee = EmitScalarExpr(E->getCallee()); 2781 return EmitCall(E->getCallee()->getType(), Callee, ReturnValue, 2782 E->arg_begin(), E->arg_end(), TargetDecl); 2783} 2784 2785LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) { 2786 // Comma expressions just emit their LHS then their RHS as an l-value. 2787 if (E->getOpcode() == BO_Comma) { 2788 EmitIgnoredExpr(E->getLHS()); 2789 EnsureInsertPoint(); 2790 return EmitLValue(E->getRHS()); 2791 } 2792 2793 if (E->getOpcode() == BO_PtrMemD || 2794 E->getOpcode() == BO_PtrMemI) 2795 return EmitPointerToDataMemberBinaryExpr(E); 2796 2797 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value"); 2798 2799 // Note that in all of these cases, __block variables need the RHS 2800 // evaluated first just in case the variable gets moved by the RHS. 2801 2802 if (!hasAggregateLLVMType(E->getType())) { 2803 switch (E->getLHS()->getType().getObjCLifetime()) { 2804 case Qualifiers::OCL_Strong: 2805 return EmitARCStoreStrong(E, /*ignored*/ false).first; 2806 2807 case Qualifiers::OCL_Autoreleasing: 2808 return EmitARCStoreAutoreleasing(E).first; 2809 2810 // No reason to do any of these differently. 2811 case Qualifiers::OCL_None: 2812 case Qualifiers::OCL_ExplicitNone: 2813 case Qualifiers::OCL_Weak: 2814 break; 2815 } 2816 2817 RValue RV = EmitAnyExpr(E->getRHS()); 2818 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store); 2819 EmitStoreThroughLValue(RV, LV); 2820 return LV; 2821 } 2822 2823 if (E->getType()->isAnyComplexType()) 2824 return EmitComplexAssignmentLValue(E); 2825 2826 return EmitAggExprToLValue(E); 2827} 2828 2829LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) { 2830 RValue RV = EmitCallExpr(E); 2831 2832 if (!RV.isScalar()) 2833 return MakeAddrLValue(RV.getAggregateAddr(), E->getType()); 2834 2835 assert(E->getCallReturnType()->isReferenceType() && 2836 "Can't have a scalar return unless the return type is a " 2837 "reference type!"); 2838 2839 return MakeAddrLValue(RV.getScalarVal(), E->getType()); 2840} 2841 2842LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) { 2843 // FIXME: This shouldn't require another copy. 2844 return EmitAggExprToLValue(E); 2845} 2846 2847LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) { 2848 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor() 2849 && "binding l-value to type which needs a temporary"); 2850 AggValueSlot Slot = CreateAggTemp(E->getType()); 2851 EmitCXXConstructExpr(E, Slot); 2852 return MakeAddrLValue(Slot.getAddr(), E->getType()); 2853} 2854 2855LValue 2856CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) { 2857 return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType()); 2858} 2859 2860LValue 2861CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) { 2862 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue"); 2863 Slot.setExternallyDestructed(); 2864 EmitAggExpr(E->getSubExpr(), Slot); 2865 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddr()); 2866 return MakeAddrLValue(Slot.getAddr(), E->getType()); 2867} 2868 2869LValue 2870CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) { 2871 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue"); 2872 EmitLambdaExpr(E, Slot); 2873 return MakeAddrLValue(Slot.getAddr(), E->getType()); 2874} 2875 2876LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) { 2877 RValue RV = EmitObjCMessageExpr(E); 2878 2879 if (!RV.isScalar()) 2880 return MakeAddrLValue(RV.getAggregateAddr(), E->getType()); 2881 2882 assert(E->getMethodDecl()->getResultType()->isReferenceType() && 2883 "Can't have a scalar return unless the return type is a " 2884 "reference type!"); 2885 2886 return MakeAddrLValue(RV.getScalarVal(), E->getType()); 2887} 2888 2889LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) { 2890 llvm::Value *V = 2891 CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true); 2892 return MakeAddrLValue(V, E->getType()); 2893} 2894 2895llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface, 2896 const ObjCIvarDecl *Ivar) { 2897 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar); 2898} 2899 2900LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy, 2901 llvm::Value *BaseValue, 2902 const ObjCIvarDecl *Ivar, 2903 unsigned CVRQualifiers) { 2904 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue, 2905 Ivar, CVRQualifiers); 2906} 2907 2908LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) { 2909 // FIXME: A lot of the code below could be shared with EmitMemberExpr. 2910 llvm::Value *BaseValue = 0; 2911 const Expr *BaseExpr = E->getBase(); 2912 Qualifiers BaseQuals; 2913 QualType ObjectTy; 2914 if (E->isArrow()) { 2915 BaseValue = EmitScalarExpr(BaseExpr); 2916 ObjectTy = BaseExpr->getType()->getPointeeType(); 2917 BaseQuals = ObjectTy.getQualifiers(); 2918 } else { 2919 LValue BaseLV = EmitLValue(BaseExpr); 2920 // FIXME: this isn't right for bitfields. 2921 BaseValue = BaseLV.getAddress(); 2922 ObjectTy = BaseExpr->getType(); 2923 BaseQuals = ObjectTy.getQualifiers(); 2924 } 2925 2926 LValue LV = 2927 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(), 2928 BaseQuals.getCVRQualifiers()); 2929 setObjCGCLValueClass(getContext(), E, LV); 2930 return LV; 2931} 2932 2933LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) { 2934 // Can only get l-value for message expression returning aggregate type 2935 RValue RV = EmitAnyExprToTemp(E); 2936 return MakeAddrLValue(RV.getAggregateAddr(), E->getType()); 2937} 2938 2939RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee, 2940 ReturnValueSlot ReturnValue, 2941 CallExpr::const_arg_iterator ArgBeg, 2942 CallExpr::const_arg_iterator ArgEnd, 2943 const Decl *TargetDecl) { 2944 // Get the actual function type. The callee type will always be a pointer to 2945 // function type or a block pointer type. 2946 assert(CalleeType->isFunctionPointerType() && 2947 "Call must have function pointer type!"); 2948 2949 CalleeType = getContext().getCanonicalType(CalleeType); 2950 2951 const FunctionType *FnType 2952 = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType()); 2953 2954 CallArgList Args; 2955 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd); 2956 2957 const CGFunctionInfo &FnInfo = 2958 CGM.getTypes().arrangeFreeFunctionCall(Args, FnType); 2959 2960 // C99 6.5.2.2p6: 2961 // If the expression that denotes the called function has a type 2962 // that does not include a prototype, [the default argument 2963 // promotions are performed]. If the number of arguments does not 2964 // equal the number of parameters, the behavior is undefined. If 2965 // the function is defined with a type that includes a prototype, 2966 // and either the prototype ends with an ellipsis (, ...) or the 2967 // types of the arguments after promotion are not compatible with 2968 // the types of the parameters, the behavior is undefined. If the 2969 // function is defined with a type that does not include a 2970 // prototype, and the types of the arguments after promotion are 2971 // not compatible with those of the parameters after promotion, 2972 // the behavior is undefined [except in some trivial cases]. 2973 // That is, in the general case, we should assume that a call 2974 // through an unprototyped function type works like a *non-variadic* 2975 // call. The way we make this work is to cast to the exact type 2976 // of the promoted arguments. 2977 if (isa<FunctionNoProtoType>(FnType) && !FnInfo.isVariadic()) { 2978 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo); 2979 CalleeTy = CalleeTy->getPointerTo(); 2980 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast"); 2981 } 2982 2983 return EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl); 2984} 2985 2986LValue CodeGenFunction:: 2987EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) { 2988 llvm::Value *BaseV; 2989 if (E->getOpcode() == BO_PtrMemI) 2990 BaseV = EmitScalarExpr(E->getLHS()); 2991 else 2992 BaseV = EmitLValue(E->getLHS()).getAddress(); 2993 2994 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS()); 2995 2996 const MemberPointerType *MPT 2997 = E->getRHS()->getType()->getAs<MemberPointerType>(); 2998 2999 llvm::Value *AddV = 3000 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, BaseV, OffsetV, MPT); 3001 3002 return MakeAddrLValue(AddV, MPT->getPointeeType()); 3003} 3004 3005static void 3006EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, llvm::Value *Dest, 3007 llvm::Value *Ptr, llvm::Value *Val1, llvm::Value *Val2, 3008 uint64_t Size, unsigned Align, llvm::AtomicOrdering Order) { 3009 llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add; 3010 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0; 3011 3012 switch (E->getOp()) { 3013 case AtomicExpr::AO__c11_atomic_init: 3014 llvm_unreachable("Already handled!"); 3015 3016 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 3017 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 3018 case AtomicExpr::AO__atomic_compare_exchange: 3019 case AtomicExpr::AO__atomic_compare_exchange_n: { 3020 // Note that cmpxchg only supports specifying one ordering and 3021 // doesn't support weak cmpxchg, at least at the moment. 3022 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1); 3023 LoadVal1->setAlignment(Align); 3024 llvm::LoadInst *LoadVal2 = CGF.Builder.CreateLoad(Val2); 3025 LoadVal2->setAlignment(Align); 3026 llvm::AtomicCmpXchgInst *CXI = 3027 CGF.Builder.CreateAtomicCmpXchg(Ptr, LoadVal1, LoadVal2, Order); 3028 CXI->setVolatile(E->isVolatile()); 3029 llvm::StoreInst *StoreVal1 = CGF.Builder.CreateStore(CXI, Val1); 3030 StoreVal1->setAlignment(Align); 3031 llvm::Value *Cmp = CGF.Builder.CreateICmpEQ(CXI, LoadVal1); 3032 CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType())); 3033 return; 3034 } 3035 3036 case AtomicExpr::AO__c11_atomic_load: 3037 case AtomicExpr::AO__atomic_load_n: 3038 case AtomicExpr::AO__atomic_load: { 3039 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr); 3040 Load->setAtomic(Order); 3041 Load->setAlignment(Size); 3042 Load->setVolatile(E->isVolatile()); 3043 llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Load, Dest); 3044 StoreDest->setAlignment(Align); 3045 return; 3046 } 3047 3048 case AtomicExpr::AO__c11_atomic_store: 3049 case AtomicExpr::AO__atomic_store: 3050 case AtomicExpr::AO__atomic_store_n: { 3051 assert(!Dest && "Store does not return a value"); 3052 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1); 3053 LoadVal1->setAlignment(Align); 3054 llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr); 3055 Store->setAtomic(Order); 3056 Store->setAlignment(Size); 3057 Store->setVolatile(E->isVolatile()); 3058 return; 3059 } 3060 3061 case AtomicExpr::AO__c11_atomic_exchange: 3062 case AtomicExpr::AO__atomic_exchange_n: 3063 case AtomicExpr::AO__atomic_exchange: 3064 Op = llvm::AtomicRMWInst::Xchg; 3065 break; 3066 3067 case AtomicExpr::AO__atomic_add_fetch: 3068 PostOp = llvm::Instruction::Add; 3069 // Fall through. 3070 case AtomicExpr::AO__c11_atomic_fetch_add: 3071 case AtomicExpr::AO__atomic_fetch_add: 3072 Op = llvm::AtomicRMWInst::Add; 3073 break; 3074 3075 case AtomicExpr::AO__atomic_sub_fetch: 3076 PostOp = llvm::Instruction::Sub; 3077 // Fall through. 3078 case AtomicExpr::AO__c11_atomic_fetch_sub: 3079 case AtomicExpr::AO__atomic_fetch_sub: 3080 Op = llvm::AtomicRMWInst::Sub; 3081 break; 3082 3083 case AtomicExpr::AO__atomic_and_fetch: 3084 PostOp = llvm::Instruction::And; 3085 // Fall through. 3086 case AtomicExpr::AO__c11_atomic_fetch_and: 3087 case AtomicExpr::AO__atomic_fetch_and: 3088 Op = llvm::AtomicRMWInst::And; 3089 break; 3090 3091 case AtomicExpr::AO__atomic_or_fetch: 3092 PostOp = llvm::Instruction::Or; 3093 // Fall through. 3094 case AtomicExpr::AO__c11_atomic_fetch_or: 3095 case AtomicExpr::AO__atomic_fetch_or: 3096 Op = llvm::AtomicRMWInst::Or; 3097 break; 3098 3099 case AtomicExpr::AO__atomic_xor_fetch: 3100 PostOp = llvm::Instruction::Xor; 3101 // Fall through. 3102 case AtomicExpr::AO__c11_atomic_fetch_xor: 3103 case AtomicExpr::AO__atomic_fetch_xor: 3104 Op = llvm::AtomicRMWInst::Xor; 3105 break; 3106 3107 case AtomicExpr::AO__atomic_nand_fetch: 3108 PostOp = llvm::Instruction::And; 3109 // Fall through. 3110 case AtomicExpr::AO__atomic_fetch_nand: 3111 Op = llvm::AtomicRMWInst::Nand; 3112 break; 3113 } 3114 3115 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1); 3116 LoadVal1->setAlignment(Align); 3117 llvm::AtomicRMWInst *RMWI = 3118 CGF.Builder.CreateAtomicRMW(Op, Ptr, LoadVal1, Order); 3119 RMWI->setVolatile(E->isVolatile()); 3120 3121 // For __atomic_*_fetch operations, perform the operation again to 3122 // determine the value which was written. 3123 llvm::Value *Result = RMWI; 3124 if (PostOp) 3125 Result = CGF.Builder.CreateBinOp(PostOp, RMWI, LoadVal1); 3126 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch) 3127 Result = CGF.Builder.CreateNot(Result); 3128 llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Result, Dest); 3129 StoreDest->setAlignment(Align); 3130} 3131 3132// This function emits any expression (scalar, complex, or aggregate) 3133// into a temporary alloca. 3134static llvm::Value * 3135EmitValToTemp(CodeGenFunction &CGF, Expr *E) { 3136 llvm::Value *DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp"); 3137 CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(), 3138 /*Init*/ true); 3139 return DeclPtr; 3140} 3141 3142static RValue ConvertTempToRValue(CodeGenFunction &CGF, QualType Ty, 3143 llvm::Value *Dest) { 3144 if (Ty->isAnyComplexType()) 3145 return RValue::getComplex(CGF.LoadComplexFromAddr(Dest, false)); 3146 if (CGF.hasAggregateLLVMType(Ty)) 3147 return RValue::getAggregate(Dest); 3148 return RValue::get(CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(Dest, Ty))); 3149} 3150 3151RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest) { 3152 QualType AtomicTy = E->getPtr()->getType()->getPointeeType(); 3153 QualType MemTy = AtomicTy; 3154 if (const AtomicType *AT = AtomicTy->getAs<AtomicType>()) 3155 MemTy = AT->getValueType(); 3156 CharUnits sizeChars = getContext().getTypeSizeInChars(AtomicTy); 3157 uint64_t Size = sizeChars.getQuantity(); 3158 CharUnits alignChars = getContext().getTypeAlignInChars(AtomicTy); 3159 unsigned Align = alignChars.getQuantity(); 3160 unsigned MaxInlineWidth = 3161 getContext().getTargetInfo().getMaxAtomicInlineWidth(); 3162 bool UseLibcall = (Size != Align || Size > MaxInlineWidth); 3163 3164 3165 3166 llvm::Value *Ptr, *Order, *OrderFail = 0, *Val1 = 0, *Val2 = 0; 3167 Ptr = EmitScalarExpr(E->getPtr()); 3168 3169 if (E->getOp() == AtomicExpr::AO__c11_atomic_init) { 3170 assert(!Dest && "Init does not return a value"); 3171 if (!hasAggregateLLVMType(E->getVal1()->getType())) { 3172 QualType PointeeType 3173 = E->getPtr()->getType()->getAs<PointerType>()->getPointeeType(); 3174 EmitScalarInit(EmitScalarExpr(E->getVal1()), 3175 LValue::MakeAddr(Ptr, PointeeType, alignChars, 3176 getContext())); 3177 } else if (E->getType()->isAnyComplexType()) { 3178 EmitComplexExprIntoAddr(E->getVal1(), Ptr, E->isVolatile()); 3179 } else { 3180 AggValueSlot Slot = AggValueSlot::forAddr(Ptr, alignChars, 3181 AtomicTy.getQualifiers(), 3182 AggValueSlot::IsNotDestructed, 3183 AggValueSlot::DoesNotNeedGCBarriers, 3184 AggValueSlot::IsNotAliased); 3185 EmitAggExpr(E->getVal1(), Slot); 3186 } 3187 return RValue::get(0); 3188 } 3189 3190 Order = EmitScalarExpr(E->getOrder()); 3191 3192 switch (E->getOp()) { 3193 case AtomicExpr::AO__c11_atomic_init: 3194 llvm_unreachable("Already handled!"); 3195 3196 case AtomicExpr::AO__c11_atomic_load: 3197 case AtomicExpr::AO__atomic_load_n: 3198 break; 3199 3200 case AtomicExpr::AO__atomic_load: 3201 Dest = EmitScalarExpr(E->getVal1()); 3202 break; 3203 3204 case AtomicExpr::AO__atomic_store: 3205 Val1 = EmitScalarExpr(E->getVal1()); 3206 break; 3207 3208 case AtomicExpr::AO__atomic_exchange: 3209 Val1 = EmitScalarExpr(E->getVal1()); 3210 Dest = EmitScalarExpr(E->getVal2()); 3211 break; 3212 3213 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 3214 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 3215 case AtomicExpr::AO__atomic_compare_exchange_n: 3216 case AtomicExpr::AO__atomic_compare_exchange: 3217 Val1 = EmitScalarExpr(E->getVal1()); 3218 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange) 3219 Val2 = EmitScalarExpr(E->getVal2()); 3220 else 3221 Val2 = EmitValToTemp(*this, E->getVal2()); 3222 OrderFail = EmitScalarExpr(E->getOrderFail()); 3223 // Evaluate and discard the 'weak' argument. 3224 if (E->getNumSubExprs() == 6) 3225 EmitScalarExpr(E->getWeak()); 3226 break; 3227 3228 case AtomicExpr::AO__c11_atomic_fetch_add: 3229 case AtomicExpr::AO__c11_atomic_fetch_sub: 3230 if (MemTy->isPointerType()) { 3231 // For pointer arithmetic, we're required to do a bit of math: 3232 // adding 1 to an int* is not the same as adding 1 to a uintptr_t. 3233 // ... but only for the C11 builtins. The GNU builtins expect the 3234 // user to multiply by sizeof(T). 3235 QualType Val1Ty = E->getVal1()->getType(); 3236 llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1()); 3237 CharUnits PointeeIncAmt = 3238 getContext().getTypeSizeInChars(MemTy->getPointeeType()); 3239 Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt)); 3240 Val1 = CreateMemTemp(Val1Ty, ".atomictmp"); 3241 EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Val1, Val1Ty)); 3242 break; 3243 } 3244 // Fall through. 3245 case AtomicExpr::AO__atomic_fetch_add: 3246 case AtomicExpr::AO__atomic_fetch_sub: 3247 case AtomicExpr::AO__atomic_add_fetch: 3248 case AtomicExpr::AO__atomic_sub_fetch: 3249 case AtomicExpr::AO__c11_atomic_store: 3250 case AtomicExpr::AO__c11_atomic_exchange: 3251 case AtomicExpr::AO__atomic_store_n: 3252 case AtomicExpr::AO__atomic_exchange_n: 3253 case AtomicExpr::AO__c11_atomic_fetch_and: 3254 case AtomicExpr::AO__c11_atomic_fetch_or: 3255 case AtomicExpr::AO__c11_atomic_fetch_xor: 3256 case AtomicExpr::AO__atomic_fetch_and: 3257 case AtomicExpr::AO__atomic_fetch_or: 3258 case AtomicExpr::AO__atomic_fetch_xor: 3259 case AtomicExpr::AO__atomic_fetch_nand: 3260 case AtomicExpr::AO__atomic_and_fetch: 3261 case AtomicExpr::AO__atomic_or_fetch: 3262 case AtomicExpr::AO__atomic_xor_fetch: 3263 case AtomicExpr::AO__atomic_nand_fetch: 3264 Val1 = EmitValToTemp(*this, E->getVal1()); 3265 break; 3266 } 3267 3268 if (!E->getType()->isVoidType() && !Dest) 3269 Dest = CreateMemTemp(E->getType(), ".atomicdst"); 3270 3271 // Use a library call. See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary . 3272 if (UseLibcall) { 3273 3274 llvm::SmallVector<QualType, 5> Params; 3275 CallArgList Args; 3276 // Size is always the first parameter 3277 Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)), 3278 getContext().getSizeType()); 3279 // Atomic address is always the second parameter 3280 Args.add(RValue::get(EmitCastToVoidPtr(Ptr)), 3281 getContext().VoidPtrTy); 3282 3283 const char* LibCallName; 3284 QualType RetTy = getContext().VoidTy; 3285 switch (E->getOp()) { 3286 // There is only one libcall for compare an exchange, because there is no 3287 // optimisation benefit possible from a libcall version of a weak compare 3288 // and exchange. 3289 // bool __atomic_compare_exchange(size_t size, void *obj, void *expected, 3290 // void *desired, int success, int failure) 3291 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 3292 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 3293 case AtomicExpr::AO__atomic_compare_exchange: 3294 case AtomicExpr::AO__atomic_compare_exchange_n: 3295 LibCallName = "__atomic_compare_exchange"; 3296 RetTy = getContext().BoolTy; 3297 Args.add(RValue::get(EmitCastToVoidPtr(Val1)), 3298 getContext().VoidPtrTy); 3299 Args.add(RValue::get(EmitCastToVoidPtr(Val2)), 3300 getContext().VoidPtrTy); 3301 Args.add(RValue::get(Order), 3302 getContext().IntTy); 3303 Order = OrderFail; 3304 break; 3305 // void __atomic_exchange(size_t size, void *mem, void *val, void *return, 3306 // int order) 3307 case AtomicExpr::AO__c11_atomic_exchange: 3308 case AtomicExpr::AO__atomic_exchange_n: 3309 case AtomicExpr::AO__atomic_exchange: 3310 LibCallName = "__atomic_exchange"; 3311 Args.add(RValue::get(EmitCastToVoidPtr(Val1)), 3312 getContext().VoidPtrTy); 3313 Args.add(RValue::get(EmitCastToVoidPtr(Dest)), 3314 getContext().VoidPtrTy); 3315 break; 3316 // void __atomic_store(size_t size, void *mem, void *val, int order) 3317 case AtomicExpr::AO__c11_atomic_store: 3318 case AtomicExpr::AO__atomic_store: 3319 case AtomicExpr::AO__atomic_store_n: 3320 LibCallName = "__atomic_store"; 3321 Args.add(RValue::get(EmitCastToVoidPtr(Val1)), 3322 getContext().VoidPtrTy); 3323 break; 3324 // void __atomic_load(size_t size, void *mem, void *return, int order) 3325 case AtomicExpr::AO__c11_atomic_load: 3326 case AtomicExpr::AO__atomic_load: 3327 case AtomicExpr::AO__atomic_load_n: 3328 LibCallName = "__atomic_load"; 3329 Args.add(RValue::get(EmitCastToVoidPtr(Dest)), 3330 getContext().VoidPtrTy); 3331 break; 3332#if 0 3333 // These are only defined for 1-16 byte integers. It is not clear what 3334 // their semantics would be on anything else... 3335 case AtomicExpr::Add: LibCallName = "__atomic_fetch_add_generic"; break; 3336 case AtomicExpr::Sub: LibCallName = "__atomic_fetch_sub_generic"; break; 3337 case AtomicExpr::And: LibCallName = "__atomic_fetch_and_generic"; break; 3338 case AtomicExpr::Or: LibCallName = "__atomic_fetch_or_generic"; break; 3339 case AtomicExpr::Xor: LibCallName = "__atomic_fetch_xor_generic"; break; 3340#endif 3341 default: return EmitUnsupportedRValue(E, "atomic library call"); 3342 } 3343 // order is always the last parameter 3344 Args.add(RValue::get(Order), 3345 getContext().IntTy); 3346 3347 const CGFunctionInfo &FuncInfo = 3348 CGM.getTypes().arrangeFreeFunctionCall(RetTy, Args, 3349 FunctionType::ExtInfo(), RequiredArgs::All); 3350 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo); 3351 llvm::Constant *Func = CGM.CreateRuntimeFunction(FTy, LibCallName); 3352 RValue Res = EmitCall(FuncInfo, Func, ReturnValueSlot(), Args); 3353 if (E->isCmpXChg()) 3354 return Res; 3355 if (E->getType()->isVoidType()) 3356 return RValue::get(0); 3357 return ConvertTempToRValue(*this, E->getType(), Dest); 3358 } 3359 3360 llvm::Type *IPtrTy = 3361 llvm::IntegerType::get(getLLVMContext(), Size * 8)->getPointerTo(); 3362 llvm::Value *OrigDest = Dest; 3363 Ptr = Builder.CreateBitCast(Ptr, IPtrTy); 3364 if (Val1) Val1 = Builder.CreateBitCast(Val1, IPtrTy); 3365 if (Val2) Val2 = Builder.CreateBitCast(Val2, IPtrTy); 3366 if (Dest && !E->isCmpXChg()) Dest = Builder.CreateBitCast(Dest, IPtrTy); 3367 3368 if (isa<llvm::ConstantInt>(Order)) { 3369 int ord = cast<llvm::ConstantInt>(Order)->getZExtValue(); 3370 switch (ord) { 3371 case 0: // memory_order_relaxed 3372 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align, 3373 llvm::Monotonic); 3374 break; 3375 case 1: // memory_order_consume 3376 case 2: // memory_order_acquire 3377 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align, 3378 llvm::Acquire); 3379 break; 3380 case 3: // memory_order_release 3381 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align, 3382 llvm::Release); 3383 break; 3384 case 4: // memory_order_acq_rel 3385 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align, 3386 llvm::AcquireRelease); 3387 break; 3388 case 5: // memory_order_seq_cst 3389 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align, 3390 llvm::SequentiallyConsistent); 3391 break; 3392 default: // invalid order 3393 // We should not ever get here normally, but it's hard to 3394 // enforce that in general. 3395 break; 3396 } 3397 if (E->getType()->isVoidType()) 3398 return RValue::get(0); 3399 return ConvertTempToRValue(*this, E->getType(), OrigDest); 3400 } 3401 3402 // Long case, when Order isn't obviously constant. 3403 3404 bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store || 3405 E->getOp() == AtomicExpr::AO__atomic_store || 3406 E->getOp() == AtomicExpr::AO__atomic_store_n; 3407 bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load || 3408 E->getOp() == AtomicExpr::AO__atomic_load || 3409 E->getOp() == AtomicExpr::AO__atomic_load_n; 3410 3411 // Create all the relevant BB's 3412 llvm::BasicBlock *MonotonicBB = 0, *AcquireBB = 0, *ReleaseBB = 0, 3413 *AcqRelBB = 0, *SeqCstBB = 0; 3414 MonotonicBB = createBasicBlock("monotonic", CurFn); 3415 if (!IsStore) 3416 AcquireBB = createBasicBlock("acquire", CurFn); 3417 if (!IsLoad) 3418 ReleaseBB = createBasicBlock("release", CurFn); 3419 if (!IsLoad && !IsStore) 3420 AcqRelBB = createBasicBlock("acqrel", CurFn); 3421 SeqCstBB = createBasicBlock("seqcst", CurFn); 3422 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn); 3423 3424 // Create the switch for the split 3425 // MonotonicBB is arbitrarily chosen as the default case; in practice, this 3426 // doesn't matter unless someone is crazy enough to use something that 3427 // doesn't fold to a constant for the ordering. 3428 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false); 3429 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB); 3430 3431 // Emit all the different atomics 3432 Builder.SetInsertPoint(MonotonicBB); 3433 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align, 3434 llvm::Monotonic); 3435 Builder.CreateBr(ContBB); 3436 if (!IsStore) { 3437 Builder.SetInsertPoint(AcquireBB); 3438 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align, 3439 llvm::Acquire); 3440 Builder.CreateBr(ContBB); 3441 SI->addCase(Builder.getInt32(1), AcquireBB); 3442 SI->addCase(Builder.getInt32(2), AcquireBB); 3443 } 3444 if (!IsLoad) { 3445 Builder.SetInsertPoint(ReleaseBB); 3446 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align, 3447 llvm::Release); 3448 Builder.CreateBr(ContBB); 3449 SI->addCase(Builder.getInt32(3), ReleaseBB); 3450 } 3451 if (!IsLoad && !IsStore) { 3452 Builder.SetInsertPoint(AcqRelBB); 3453 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align, 3454 llvm::AcquireRelease); 3455 Builder.CreateBr(ContBB); 3456 SI->addCase(Builder.getInt32(4), AcqRelBB); 3457 } 3458 Builder.SetInsertPoint(SeqCstBB); 3459 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align, 3460 llvm::SequentiallyConsistent); 3461 Builder.CreateBr(ContBB); 3462 SI->addCase(Builder.getInt32(5), SeqCstBB); 3463 3464 // Cleanup and return 3465 Builder.SetInsertPoint(ContBB); 3466 if (E->getType()->isVoidType()) 3467 return RValue::get(0); 3468 return ConvertTempToRValue(*this, E->getType(), OrigDest); 3469} 3470 3471void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) { 3472 assert(Val->getType()->isFPOrFPVectorTy()); 3473 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val)) 3474 return; 3475 3476 llvm::MDBuilder MDHelper(getLLVMContext()); 3477 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy); 3478 3479 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node); 3480} 3481 3482namespace { 3483 struct LValueOrRValue { 3484 LValue LV; 3485 RValue RV; 3486 }; 3487} 3488 3489static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF, 3490 const PseudoObjectExpr *E, 3491 bool forLValue, 3492 AggValueSlot slot) { 3493 llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques; 3494 3495 // Find the result expression, if any. 3496 const Expr *resultExpr = E->getResultExpr(); 3497 LValueOrRValue result; 3498 3499 for (PseudoObjectExpr::const_semantics_iterator 3500 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) { 3501 const Expr *semantic = *i; 3502 3503 // If this semantic expression is an opaque value, bind it 3504 // to the result of its source expression. 3505 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) { 3506 3507 // If this is the result expression, we may need to evaluate 3508 // directly into the slot. 3509 typedef CodeGenFunction::OpaqueValueMappingData OVMA; 3510 OVMA opaqueData; 3511 if (ov == resultExpr && ov->isRValue() && !forLValue && 3512 CodeGenFunction::hasAggregateLLVMType(ov->getType()) && 3513 !ov->getType()->isAnyComplexType()) { 3514 CGF.EmitAggExpr(ov->getSourceExpr(), slot); 3515 3516 LValue LV = CGF.MakeAddrLValue(slot.getAddr(), ov->getType()); 3517 opaqueData = OVMA::bind(CGF, ov, LV); 3518 result.RV = slot.asRValue(); 3519 3520 // Otherwise, emit as normal. 3521 } else { 3522 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr()); 3523 3524 // If this is the result, also evaluate the result now. 3525 if (ov == resultExpr) { 3526 if (forLValue) 3527 result.LV = CGF.EmitLValue(ov); 3528 else 3529 result.RV = CGF.EmitAnyExpr(ov, slot); 3530 } 3531 } 3532 3533 opaques.push_back(opaqueData); 3534 3535 // Otherwise, if the expression is the result, evaluate it 3536 // and remember the result. 3537 } else if (semantic == resultExpr) { 3538 if (forLValue) 3539 result.LV = CGF.EmitLValue(semantic); 3540 else 3541 result.RV = CGF.EmitAnyExpr(semantic, slot); 3542 3543 // Otherwise, evaluate the expression in an ignored context. 3544 } else { 3545 CGF.EmitIgnoredExpr(semantic); 3546 } 3547 } 3548 3549 // Unbind all the opaques now. 3550 for (unsigned i = 0, e = opaques.size(); i != e; ++i) 3551 opaques[i].unbind(CGF); 3552 3553 return result; 3554} 3555 3556RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E, 3557 AggValueSlot slot) { 3558 return emitPseudoObjectExpr(*this, E, false, slot).RV; 3559} 3560 3561LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) { 3562 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV; 3563} 3564