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