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