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