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