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