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