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