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