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