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