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