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::FixedVectorType::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 auto *vec4Ty = llvm::FixedVectorType::get(VTy->getElementType(), 4); 1682 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4"); 1683 // Now load value. 1684 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4"); 1685 1686 // Shuffle vector to get vec3. 1687 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty), 1688 ArrayRef<int>{0, 1, 2}, "extractVec"); 1689 return EmitFromMemory(V, Ty); 1690 } 1691 } 1692 } 1693 1694 // Atomic operations have to be done on integral types. 1695 LValue AtomicLValue = 1696 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo); 1697 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) { 1698 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal(); 1699 } 1700 1701 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile); 1702 if (isNontemporal) { 1703 llvm::MDNode *Node = llvm::MDNode::get( 1704 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1))); 1705 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node); 1706 } 1707 1708 CGM.DecorateInstructionWithTBAA(Load, TBAAInfo); 1709 1710 if (EmitScalarRangeCheck(Load, Ty, Loc)) { 1711 // In order to prevent the optimizer from throwing away the check, don't 1712 // attach range metadata to the load. 1713 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0) 1714 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty)) 1715 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo); 1716 1717 return EmitFromMemory(Load, Ty); 1718 } 1719 1720 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) { 1721 // Bool has a different representation in memory than in registers. 1722 if (hasBooleanRepresentation(Ty)) { 1723 // This should really always be an i1, but sometimes it's already 1724 // an i8, and it's awkward to track those cases down. 1725 if (Value->getType()->isIntegerTy(1)) 1726 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool"); 1727 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) && 1728 "wrong value rep of bool"); 1729 } 1730 1731 return Value; 1732 } 1733 1734 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) { 1735 // Bool has a different representation in memory than in registers. 1736 if (hasBooleanRepresentation(Ty)) { 1737 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) && 1738 "wrong value rep of bool"); 1739 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool"); 1740 } 1741 1742 return Value; 1743 } 1744 1745 // Convert the pointer of \p Addr to a pointer to a vector (the value type of 1746 // MatrixType), if it points to a array (the memory type of MatrixType). 1747 static Address MaybeConvertMatrixAddress(Address Addr, CodeGenFunction &CGF, 1748 bool IsVector = true) { 1749 auto *ArrayTy = dyn_cast<llvm::ArrayType>( 1750 cast<llvm::PointerType>(Addr.getPointer()->getType())->getElementType()); 1751 if (ArrayTy && IsVector) { 1752 auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(), 1753 ArrayTy->getNumElements()); 1754 1755 return Address(CGF.Builder.CreateElementBitCast(Addr, VectorTy)); 1756 } 1757 auto *VectorTy = dyn_cast<llvm::VectorType>( 1758 cast<llvm::PointerType>(Addr.getPointer()->getType())->getElementType()); 1759 if (VectorTy && !IsVector) { 1760 auto *ArrayTy = llvm::ArrayType::get(VectorTy->getElementType(), 1761 VectorTy->getNumElements()); 1762 1763 return Address(CGF.Builder.CreateElementBitCast(Addr, ArrayTy)); 1764 } 1765 1766 return Addr; 1767 } 1768 1769 // Emit a store of a matrix LValue. This may require casting the original 1770 // pointer to memory address (ArrayType) to a pointer to the value type 1771 // (VectorType). 1772 static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue, 1773 bool isInit, CodeGenFunction &CGF) { 1774 Address Addr = MaybeConvertMatrixAddress(lvalue.getAddress(CGF), CGF, 1775 value->getType()->isVectorTy()); 1776 CGF.EmitStoreOfScalar(value, Addr, lvalue.isVolatile(), lvalue.getType(), 1777 lvalue.getBaseInfo(), lvalue.getTBAAInfo(), isInit, 1778 lvalue.isNontemporal()); 1779 } 1780 1781 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr, 1782 bool Volatile, QualType Ty, 1783 LValueBaseInfo BaseInfo, 1784 TBAAAccessInfo TBAAInfo, 1785 bool isInit, bool isNontemporal) { 1786 if (!CGM.getCodeGenOpts().PreserveVec3Type) { 1787 // Handle vectors differently to get better performance. 1788 if (Ty->isVectorType()) { 1789 llvm::Type *SrcTy = Value->getType(); 1790 auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy); 1791 // Handle vec3 special. 1792 if (VecTy && VecTy->getNumElements() == 3) { 1793 // Our source is a vec3, do a shuffle vector to make it a vec4. 1794 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy), 1795 ArrayRef<int>{0, 1, 2, -1}, 1796 "extractVec"); 1797 SrcTy = llvm::FixedVectorType::get(VecTy->getElementType(), 4); 1798 } 1799 if (Addr.getElementType() != SrcTy) { 1800 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp"); 1801 } 1802 } 1803 } 1804 1805 Value = EmitToMemory(Value, Ty); 1806 1807 LValue AtomicLValue = 1808 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo); 1809 if (Ty->isAtomicType() || 1810 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) { 1811 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit); 1812 return; 1813 } 1814 1815 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile); 1816 if (isNontemporal) { 1817 llvm::MDNode *Node = 1818 llvm::MDNode::get(Store->getContext(), 1819 llvm::ConstantAsMetadata::get(Builder.getInt32(1))); 1820 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node); 1821 } 1822 1823 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo); 1824 } 1825 1826 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue, 1827 bool isInit) { 1828 if (lvalue.getType()->isConstantMatrixType()) { 1829 EmitStoreOfMatrixScalar(value, lvalue, isInit, *this); 1830 return; 1831 } 1832 1833 EmitStoreOfScalar(value, lvalue.getAddress(*this), lvalue.isVolatile(), 1834 lvalue.getType(), lvalue.getBaseInfo(), 1835 lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal()); 1836 } 1837 1838 // Emit a load of a LValue of matrix type. This may require casting the pointer 1839 // to memory address (ArrayType) to a pointer to the value type (VectorType). 1840 static RValue EmitLoadOfMatrixLValue(LValue LV, SourceLocation Loc, 1841 CodeGenFunction &CGF) { 1842 assert(LV.getType()->isConstantMatrixType()); 1843 Address Addr = MaybeConvertMatrixAddress(LV.getAddress(CGF), CGF); 1844 LV.setAddress(Addr); 1845 return RValue::get(CGF.EmitLoadOfScalar(LV, Loc)); 1846 } 1847 1848 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this 1849 /// method emits the address of the lvalue, then loads the result as an rvalue, 1850 /// returning the rvalue. 1851 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) { 1852 if (LV.isObjCWeak()) { 1853 // load of a __weak object. 1854 Address AddrWeakObj = LV.getAddress(*this); 1855 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this, 1856 AddrWeakObj)); 1857 } 1858 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) { 1859 // In MRC mode, we do a load+autorelease. 1860 if (!getLangOpts().ObjCAutoRefCount) { 1861 return RValue::get(EmitARCLoadWeak(LV.getAddress(*this))); 1862 } 1863 1864 // In ARC mode, we load retained and then consume the value. 1865 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress(*this)); 1866 Object = EmitObjCConsumeObject(LV.getType(), Object); 1867 return RValue::get(Object); 1868 } 1869 1870 if (LV.isSimple()) { 1871 assert(!LV.getType()->isFunctionType()); 1872 1873 if (LV.getType()->isConstantMatrixType()) 1874 return EmitLoadOfMatrixLValue(LV, Loc, *this); 1875 1876 // Everything needs a load. 1877 return RValue::get(EmitLoadOfScalar(LV, Loc)); 1878 } 1879 1880 if (LV.isVectorElt()) { 1881 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(), 1882 LV.isVolatileQualified()); 1883 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(), 1884 "vecext")); 1885 } 1886 1887 // If this is a reference to a subset of the elements of a vector, either 1888 // shuffle the input or extract/insert them as appropriate. 1889 if (LV.isExtVectorElt()) 1890 return EmitLoadOfExtVectorElementLValue(LV); 1891 1892 // Global Register variables always invoke intrinsics 1893 if (LV.isGlobalReg()) 1894 return EmitLoadOfGlobalRegLValue(LV); 1895 1896 assert(LV.isBitField() && "Unknown LValue type!"); 1897 return EmitLoadOfBitfieldLValue(LV, Loc); 1898 } 1899 1900 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV, 1901 SourceLocation Loc) { 1902 const CGBitFieldInfo &Info = LV.getBitFieldInfo(); 1903 1904 // Get the output type. 1905 llvm::Type *ResLTy = ConvertType(LV.getType()); 1906 1907 Address Ptr = LV.getBitFieldAddress(); 1908 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load"); 1909 1910 if (Info.IsSigned) { 1911 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize); 1912 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size; 1913 if (HighBits) 1914 Val = Builder.CreateShl(Val, HighBits, "bf.shl"); 1915 if (Info.Offset + HighBits) 1916 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr"); 1917 } else { 1918 if (Info.Offset) 1919 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr"); 1920 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize) 1921 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize, 1922 Info.Size), 1923 "bf.clear"); 1924 } 1925 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast"); 1926 EmitScalarRangeCheck(Val, LV.getType(), Loc); 1927 return RValue::get(Val); 1928 } 1929 1930 // If this is a reference to a subset of the elements of a vector, create an 1931 // appropriate shufflevector. 1932 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) { 1933 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(), 1934 LV.isVolatileQualified()); 1935 1936 const llvm::Constant *Elts = LV.getExtVectorElts(); 1937 1938 // If the result of the expression is a non-vector type, we must be extracting 1939 // a single element. Just codegen as an extractelement. 1940 const VectorType *ExprVT = LV.getType()->getAs<VectorType>(); 1941 if (!ExprVT) { 1942 unsigned InIdx = getAccessedFieldNo(0, Elts); 1943 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx); 1944 return RValue::get(Builder.CreateExtractElement(Vec, Elt)); 1945 } 1946 1947 // Always use shuffle vector to try to retain the original program structure 1948 unsigned NumResultElts = ExprVT->getNumElements(); 1949 1950 SmallVector<int, 4> Mask; 1951 for (unsigned i = 0; i != NumResultElts; ++i) 1952 Mask.push_back(getAccessedFieldNo(i, Elts)); 1953 1954 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()), 1955 Mask); 1956 return RValue::get(Vec); 1957 } 1958 1959 /// Generates lvalue for partial ext_vector access. 1960 Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) { 1961 Address VectorAddress = LV.getExtVectorAddress(); 1962 QualType EQT = LV.getType()->castAs<VectorType>()->getElementType(); 1963 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT); 1964 1965 Address CastToPointerElement = 1966 Builder.CreateElementBitCast(VectorAddress, VectorElementTy, 1967 "conv.ptr.element"); 1968 1969 const llvm::Constant *Elts = LV.getExtVectorElts(); 1970 unsigned ix = getAccessedFieldNo(0, Elts); 1971 1972 Address VectorBasePtrPlusIx = 1973 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix, 1974 "vector.elt"); 1975 1976 return VectorBasePtrPlusIx; 1977 } 1978 1979 /// Load of global gamed gegisters are always calls to intrinsics. 1980 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) { 1981 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) && 1982 "Bad type for register variable"); 1983 llvm::MDNode *RegName = cast<llvm::MDNode>( 1984 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata()); 1985 1986 // We accept integer and pointer types only 1987 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType()); 1988 llvm::Type *Ty = OrigTy; 1989 if (OrigTy->isPointerTy()) 1990 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy); 1991 llvm::Type *Types[] = { Ty }; 1992 1993 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types); 1994 llvm::Value *Call = Builder.CreateCall( 1995 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName)); 1996 if (OrigTy->isPointerTy()) 1997 Call = Builder.CreateIntToPtr(Call, OrigTy); 1998 return RValue::get(Call); 1999 } 2000 2001 2002 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 2003 /// lvalue, where both are guaranteed to the have the same type, and that type 2004 /// is 'Ty'. 2005 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, 2006 bool isInit) { 2007 if (!Dst.isSimple()) { 2008 if (Dst.isVectorElt()) { 2009 // Read/modify/write the vector, inserting the new element. 2010 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(), 2011 Dst.isVolatileQualified()); 2012 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(), 2013 Dst.getVectorIdx(), "vecins"); 2014 Builder.CreateStore(Vec, Dst.getVectorAddress(), 2015 Dst.isVolatileQualified()); 2016 return; 2017 } 2018 2019 // If this is an update of extended vector elements, insert them as 2020 // appropriate. 2021 if (Dst.isExtVectorElt()) 2022 return EmitStoreThroughExtVectorComponentLValue(Src, Dst); 2023 2024 if (Dst.isGlobalReg()) 2025 return EmitStoreThroughGlobalRegLValue(Src, Dst); 2026 2027 assert(Dst.isBitField() && "Unknown LValue type"); 2028 return EmitStoreThroughBitfieldLValue(Src, Dst); 2029 } 2030 2031 // There's special magic for assigning into an ARC-qualified l-value. 2032 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) { 2033 switch (Lifetime) { 2034 case Qualifiers::OCL_None: 2035 llvm_unreachable("present but none"); 2036 2037 case Qualifiers::OCL_ExplicitNone: 2038 // nothing special 2039 break; 2040 2041 case Qualifiers::OCL_Strong: 2042 if (isInit) { 2043 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal())); 2044 break; 2045 } 2046 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true); 2047 return; 2048 2049 case Qualifiers::OCL_Weak: 2050 if (isInit) 2051 // Initialize and then skip the primitive store. 2052 EmitARCInitWeak(Dst.getAddress(*this), Src.getScalarVal()); 2053 else 2054 EmitARCStoreWeak(Dst.getAddress(*this), Src.getScalarVal(), 2055 /*ignore*/ true); 2056 return; 2057 2058 case Qualifiers::OCL_Autoreleasing: 2059 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(), 2060 Src.getScalarVal())); 2061 // fall into the normal path 2062 break; 2063 } 2064 } 2065 2066 if (Dst.isObjCWeak() && !Dst.isNonGC()) { 2067 // load of a __weak object. 2068 Address LvalueDst = Dst.getAddress(*this); 2069 llvm::Value *src = Src.getScalarVal(); 2070 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst); 2071 return; 2072 } 2073 2074 if (Dst.isObjCStrong() && !Dst.isNonGC()) { 2075 // load of a __strong object. 2076 Address LvalueDst = Dst.getAddress(*this); 2077 llvm::Value *src = Src.getScalarVal(); 2078 if (Dst.isObjCIvar()) { 2079 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL"); 2080 llvm::Type *ResultType = IntPtrTy; 2081 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp()); 2082 llvm::Value *RHS = dst.getPointer(); 2083 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast"); 2084 llvm::Value *LHS = 2085 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType, 2086 "sub.ptr.lhs.cast"); 2087 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset"); 2088 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst, 2089 BytesBetween); 2090 } else if (Dst.isGlobalObjCRef()) { 2091 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst, 2092 Dst.isThreadLocalRef()); 2093 } 2094 else 2095 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst); 2096 return; 2097 } 2098 2099 assert(Src.isScalar() && "Can't emit an agg store with this method"); 2100 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit); 2101 } 2102 2103 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 2104 llvm::Value **Result) { 2105 const CGBitFieldInfo &Info = Dst.getBitFieldInfo(); 2106 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType()); 2107 Address Ptr = Dst.getBitFieldAddress(); 2108 2109 // Get the source value, truncated to the width of the bit-field. 2110 llvm::Value *SrcVal = Src.getScalarVal(); 2111 2112 // Cast the source to the storage type and shift it into place. 2113 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(), 2114 /*isSigned=*/false); 2115 llvm::Value *MaskedVal = SrcVal; 2116 2117 // See if there are other bits in the bitfield's storage we'll need to load 2118 // and mask together with source before storing. 2119 if (Info.StorageSize != Info.Size) { 2120 assert(Info.StorageSize > Info.Size && "Invalid bitfield size."); 2121 llvm::Value *Val = 2122 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load"); 2123 2124 // Mask the source value as needed. 2125 if (!hasBooleanRepresentation(Dst.getType())) 2126 SrcVal = Builder.CreateAnd(SrcVal, 2127 llvm::APInt::getLowBitsSet(Info.StorageSize, 2128 Info.Size), 2129 "bf.value"); 2130 MaskedVal = SrcVal; 2131 if (Info.Offset) 2132 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl"); 2133 2134 // Mask out the original value. 2135 Val = Builder.CreateAnd(Val, 2136 ~llvm::APInt::getBitsSet(Info.StorageSize, 2137 Info.Offset, 2138 Info.Offset + Info.Size), 2139 "bf.clear"); 2140 2141 // Or together the unchanged values and the source value. 2142 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set"); 2143 } else { 2144 assert(Info.Offset == 0); 2145 // According to the AACPS: 2146 // When a volatile bit-field is written, and its container does not overlap 2147 // with any non-bit-field member, its container must be read exactly once and 2148 // written exactly once using the access width appropriate to the type of the 2149 // container. The two accesses are not atomic. 2150 if (Dst.isVolatileQualified() && isAAPCS(CGM.getTarget()) && 2151 CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad) 2152 Builder.CreateLoad(Ptr, true, "bf.load"); 2153 } 2154 2155 // Write the new value back out. 2156 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified()); 2157 2158 // Return the new value of the bit-field, if requested. 2159 if (Result) { 2160 llvm::Value *ResultVal = MaskedVal; 2161 2162 // Sign extend the value if needed. 2163 if (Info.IsSigned) { 2164 assert(Info.Size <= Info.StorageSize); 2165 unsigned HighBits = Info.StorageSize - Info.Size; 2166 if (HighBits) { 2167 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl"); 2168 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr"); 2169 } 2170 } 2171 2172 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned, 2173 "bf.result.cast"); 2174 *Result = EmitFromMemory(ResultVal, Dst.getType()); 2175 } 2176 } 2177 2178 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src, 2179 LValue Dst) { 2180 // This access turns into a read/modify/write of the vector. Load the input 2181 // value now. 2182 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(), 2183 Dst.isVolatileQualified()); 2184 const llvm::Constant *Elts = Dst.getExtVectorElts(); 2185 2186 llvm::Value *SrcVal = Src.getScalarVal(); 2187 2188 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) { 2189 unsigned NumSrcElts = VTy->getNumElements(); 2190 unsigned NumDstElts = 2191 cast<llvm::VectorType>(Vec->getType())->getNumElements(); 2192 if (NumDstElts == NumSrcElts) { 2193 // Use shuffle vector is the src and destination are the same number of 2194 // elements and restore the vector mask since it is on the side it will be 2195 // stored. 2196 SmallVector<int, 4> Mask(NumDstElts); 2197 for (unsigned i = 0; i != NumSrcElts; ++i) 2198 Mask[getAccessedFieldNo(i, Elts)] = i; 2199 2200 Vec = Builder.CreateShuffleVector( 2201 SrcVal, llvm::UndefValue::get(Vec->getType()), Mask); 2202 } else if (NumDstElts > NumSrcElts) { 2203 // Extended the source vector to the same length and then shuffle it 2204 // into the destination. 2205 // FIXME: since we're shuffling with undef, can we just use the indices 2206 // into that? This could be simpler. 2207 SmallVector<int, 4> ExtMask; 2208 for (unsigned i = 0; i != NumSrcElts; ++i) 2209 ExtMask.push_back(i); 2210 ExtMask.resize(NumDstElts, -1); 2211 llvm::Value *ExtSrcVal = Builder.CreateShuffleVector( 2212 SrcVal, llvm::UndefValue::get(SrcVal->getType()), ExtMask); 2213 // build identity 2214 SmallVector<int, 4> Mask; 2215 for (unsigned i = 0; i != NumDstElts; ++i) 2216 Mask.push_back(i); 2217 2218 // When the vector size is odd and .odd or .hi is used, the last element 2219 // of the Elts constant array will be one past the size of the vector. 2220 // Ignore the last element here, if it is greater than the mask size. 2221 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size()) 2222 NumSrcElts--; 2223 2224 // modify when what gets shuffled in 2225 for (unsigned i = 0; i != NumSrcElts; ++i) 2226 Mask[getAccessedFieldNo(i, Elts)] = i + NumDstElts; 2227 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, Mask); 2228 } else { 2229 // We should never shorten the vector 2230 llvm_unreachable("unexpected shorten vector length"); 2231 } 2232 } else { 2233 // If the Src is a scalar (not a vector) it must be updating one element. 2234 unsigned InIdx = getAccessedFieldNo(0, Elts); 2235 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx); 2236 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt); 2237 } 2238 2239 Builder.CreateStore(Vec, Dst.getExtVectorAddress(), 2240 Dst.isVolatileQualified()); 2241 } 2242 2243 /// Store of global named registers are always calls to intrinsics. 2244 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) { 2245 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) && 2246 "Bad type for register variable"); 2247 llvm::MDNode *RegName = cast<llvm::MDNode>( 2248 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata()); 2249 assert(RegName && "Register LValue is not metadata"); 2250 2251 // We accept integer and pointer types only 2252 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType()); 2253 llvm::Type *Ty = OrigTy; 2254 if (OrigTy->isPointerTy()) 2255 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy); 2256 llvm::Type *Types[] = { Ty }; 2257 2258 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types); 2259 llvm::Value *Value = Src.getScalarVal(); 2260 if (OrigTy->isPointerTy()) 2261 Value = Builder.CreatePtrToInt(Value, Ty); 2262 Builder.CreateCall( 2263 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value}); 2264 } 2265 2266 // setObjCGCLValueClass - sets class of the lvalue for the purpose of 2267 // generating write-barries API. It is currently a global, ivar, 2268 // or neither. 2269 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E, 2270 LValue &LV, 2271 bool IsMemberAccess=false) { 2272 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC) 2273 return; 2274 2275 if (isa<ObjCIvarRefExpr>(E)) { 2276 QualType ExpTy = E->getType(); 2277 if (IsMemberAccess && ExpTy->isPointerType()) { 2278 // If ivar is a structure pointer, assigning to field of 2279 // this struct follows gcc's behavior and makes it a non-ivar 2280 // writer-barrier conservatively. 2281 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType(); 2282 if (ExpTy->isRecordType()) { 2283 LV.setObjCIvar(false); 2284 return; 2285 } 2286 } 2287 LV.setObjCIvar(true); 2288 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E)); 2289 LV.setBaseIvarExp(Exp->getBase()); 2290 LV.setObjCArray(E->getType()->isArrayType()); 2291 return; 2292 } 2293 2294 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) { 2295 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) { 2296 if (VD->hasGlobalStorage()) { 2297 LV.setGlobalObjCRef(true); 2298 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None); 2299 } 2300 } 2301 LV.setObjCArray(E->getType()->isArrayType()); 2302 return; 2303 } 2304 2305 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) { 2306 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 2307 return; 2308 } 2309 2310 if (const auto *Exp = dyn_cast<ParenExpr>(E)) { 2311 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 2312 if (LV.isObjCIvar()) { 2313 // If cast is to a structure pointer, follow gcc's behavior and make it 2314 // a non-ivar write-barrier. 2315 QualType ExpTy = E->getType(); 2316 if (ExpTy->isPointerType()) 2317 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType(); 2318 if (ExpTy->isRecordType()) 2319 LV.setObjCIvar(false); 2320 } 2321 return; 2322 } 2323 2324 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) { 2325 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV); 2326 return; 2327 } 2328 2329 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) { 2330 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 2331 return; 2332 } 2333 2334 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) { 2335 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 2336 return; 2337 } 2338 2339 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) { 2340 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 2341 return; 2342 } 2343 2344 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) { 2345 setObjCGCLValueClass(Ctx, Exp->getBase(), LV); 2346 if (LV.isObjCIvar() && !LV.isObjCArray()) 2347 // Using array syntax to assigning to what an ivar points to is not 2348 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0; 2349 LV.setObjCIvar(false); 2350 else if (LV.isGlobalObjCRef() && !LV.isObjCArray()) 2351 // Using array syntax to assigning to what global points to is not 2352 // same as assigning to the global itself. {id *G;} G[i] = 0; 2353 LV.setGlobalObjCRef(false); 2354 return; 2355 } 2356 2357 if (const auto *Exp = dyn_cast<MemberExpr>(E)) { 2358 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true); 2359 // We don't know if member is an 'ivar', but this flag is looked at 2360 // only in the context of LV.isObjCIvar(). 2361 LV.setObjCArray(E->getType()->isArrayType()); 2362 return; 2363 } 2364 } 2365 2366 static llvm::Value * 2367 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF, 2368 llvm::Value *V, llvm::Type *IRType, 2369 StringRef Name = StringRef()) { 2370 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace(); 2371 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name); 2372 } 2373 2374 static LValue EmitThreadPrivateVarDeclLValue( 2375 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr, 2376 llvm::Type *RealVarTy, SourceLocation Loc) { 2377 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc); 2378 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy); 2379 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl); 2380 } 2381 2382 static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF, 2383 const VarDecl *VD, QualType T) { 2384 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 2385 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 2386 // Return an invalid address if variable is MT_To and unified 2387 // memory is not enabled. For all other cases: MT_Link and 2388 // MT_To with unified memory, return a valid address. 2389 if (!Res || (*Res == OMPDeclareTargetDeclAttr::MT_To && 2390 !CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) 2391 return Address::invalid(); 2392 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) || 2393 (*Res == OMPDeclareTargetDeclAttr::MT_To && 2394 CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) && 2395 "Expected link clause OR to clause with unified memory enabled."); 2396 QualType PtrTy = CGF.getContext().getPointerType(VD->getType()); 2397 Address Addr = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD); 2398 return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>()); 2399 } 2400 2401 Address 2402 CodeGenFunction::EmitLoadOfReference(LValue RefLVal, 2403 LValueBaseInfo *PointeeBaseInfo, 2404 TBAAAccessInfo *PointeeTBAAInfo) { 2405 llvm::LoadInst *Load = 2406 Builder.CreateLoad(RefLVal.getAddress(*this), RefLVal.isVolatile()); 2407 CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo()); 2408 2409 CharUnits Align = CGM.getNaturalTypeAlignment( 2410 RefLVal.getType()->getPointeeType(), PointeeBaseInfo, PointeeTBAAInfo, 2411 /* forPointeeType= */ true); 2412 return Address(Load, Align); 2413 } 2414 2415 LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) { 2416 LValueBaseInfo PointeeBaseInfo; 2417 TBAAAccessInfo PointeeTBAAInfo; 2418 Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo, 2419 &PointeeTBAAInfo); 2420 return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(), 2421 PointeeBaseInfo, PointeeTBAAInfo); 2422 } 2423 2424 Address CodeGenFunction::EmitLoadOfPointer(Address Ptr, 2425 const PointerType *PtrTy, 2426 LValueBaseInfo *BaseInfo, 2427 TBAAAccessInfo *TBAAInfo) { 2428 llvm::Value *Addr = Builder.CreateLoad(Ptr); 2429 return Address(Addr, CGM.getNaturalTypeAlignment(PtrTy->getPointeeType(), 2430 BaseInfo, TBAAInfo, 2431 /*forPointeeType=*/true)); 2432 } 2433 2434 LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr, 2435 const PointerType *PtrTy) { 2436 LValueBaseInfo BaseInfo; 2437 TBAAAccessInfo TBAAInfo; 2438 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo); 2439 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo); 2440 } 2441 2442 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF, 2443 const Expr *E, const VarDecl *VD) { 2444 QualType T = E->getType(); 2445 2446 // If it's thread_local, emit a call to its wrapper function instead. 2447 if (VD->getTLSKind() == VarDecl::TLS_Dynamic && 2448 CGF.CGM.getCXXABI().usesThreadWrapperFunction(VD)) 2449 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T); 2450 // Check if the variable is marked as declare target with link clause in 2451 // device codegen. 2452 if (CGF.getLangOpts().OpenMPIsDevice) { 2453 Address Addr = emitDeclTargetVarDeclLValue(CGF, VD, T); 2454 if (Addr.isValid()) 2455 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl); 2456 } 2457 2458 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD); 2459 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType()); 2460 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy); 2461 CharUnits Alignment = CGF.getContext().getDeclAlign(VD); 2462 Address Addr(V, Alignment); 2463 // Emit reference to the private copy of the variable if it is an OpenMP 2464 // threadprivate variable. 2465 if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd && 2466 VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 2467 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy, 2468 E->getExprLoc()); 2469 } 2470 LValue LV = VD->getType()->isReferenceType() ? 2471 CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(), 2472 AlignmentSource::Decl) : 2473 CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl); 2474 setObjCGCLValueClass(CGF.getContext(), E, LV); 2475 return LV; 2476 } 2477 2478 static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM, 2479 GlobalDecl GD) { 2480 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 2481 if (FD->hasAttr<WeakRefAttr>()) { 2482 ConstantAddress aliasee = CGM.GetWeakRefReference(FD); 2483 return aliasee.getPointer(); 2484 } 2485 2486 llvm::Constant *V = CGM.GetAddrOfFunction(GD); 2487 if (!FD->hasPrototype()) { 2488 if (const FunctionProtoType *Proto = 2489 FD->getType()->getAs<FunctionProtoType>()) { 2490 // Ugly case: for a K&R-style definition, the type of the definition 2491 // isn't the same as the type of a use. Correct for this with a 2492 // bitcast. 2493 QualType NoProtoType = 2494 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType()); 2495 NoProtoType = CGM.getContext().getPointerType(NoProtoType); 2496 V = llvm::ConstantExpr::getBitCast(V, 2497 CGM.getTypes().ConvertType(NoProtoType)); 2498 } 2499 } 2500 return V; 2501 } 2502 2503 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E, 2504 GlobalDecl GD) { 2505 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 2506 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, GD); 2507 CharUnits Alignment = CGF.getContext().getDeclAlign(FD); 2508 return CGF.MakeAddrLValue(V, E->getType(), Alignment, 2509 AlignmentSource::Decl); 2510 } 2511 2512 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD, 2513 llvm::Value *ThisValue) { 2514 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent()); 2515 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType); 2516 return CGF.EmitLValueForField(LV, FD); 2517 } 2518 2519 /// Named Registers are named metadata pointing to the register name 2520 /// which will be read from/written to as an argument to the intrinsic 2521 /// @llvm.read/write_register. 2522 /// So far, only the name is being passed down, but other options such as 2523 /// register type, allocation type or even optimization options could be 2524 /// passed down via the metadata node. 2525 static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) { 2526 SmallString<64> Name("llvm.named.register."); 2527 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>(); 2528 assert(Asm->getLabel().size() < 64-Name.size() && 2529 "Register name too big"); 2530 Name.append(Asm->getLabel()); 2531 llvm::NamedMDNode *M = 2532 CGM.getModule().getOrInsertNamedMetadata(Name); 2533 if (M->getNumOperands() == 0) { 2534 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(), 2535 Asm->getLabel()); 2536 llvm::Metadata *Ops[] = {Str}; 2537 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 2538 } 2539 2540 CharUnits Alignment = CGM.getContext().getDeclAlign(VD); 2541 2542 llvm::Value *Ptr = 2543 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0)); 2544 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType()); 2545 } 2546 2547 /// Determine whether we can emit a reference to \p VD from the current 2548 /// context, despite not necessarily having seen an odr-use of the variable in 2549 /// this context. 2550 static bool canEmitSpuriousReferenceToVariable(CodeGenFunction &CGF, 2551 const DeclRefExpr *E, 2552 const VarDecl *VD, 2553 bool IsConstant) { 2554 // For a variable declared in an enclosing scope, do not emit a spurious 2555 // reference even if we have a capture, as that will emit an unwarranted 2556 // reference to our capture state, and will likely generate worse code than 2557 // emitting a local copy. 2558 if (E->refersToEnclosingVariableOrCapture()) 2559 return false; 2560 2561 // For a local declaration declared in this function, we can always reference 2562 // it even if we don't have an odr-use. 2563 if (VD->hasLocalStorage()) { 2564 return VD->getDeclContext() == 2565 dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl); 2566 } 2567 2568 // For a global declaration, we can emit a reference to it if we know 2569 // for sure that we are able to emit a definition of it. 2570 VD = VD->getDefinition(CGF.getContext()); 2571 if (!VD) 2572 return false; 2573 2574 // Don't emit a spurious reference if it might be to a variable that only 2575 // exists on a different device / target. 2576 // FIXME: This is unnecessarily broad. Check whether this would actually be a 2577 // cross-target reference. 2578 if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA || 2579 CGF.getLangOpts().OpenCL) { 2580 return false; 2581 } 2582 2583 // We can emit a spurious reference only if the linkage implies that we'll 2584 // be emitting a non-interposable symbol that will be retained until link 2585 // time. 2586 switch (CGF.CGM.getLLVMLinkageVarDefinition(VD, IsConstant)) { 2587 case llvm::GlobalValue::ExternalLinkage: 2588 case llvm::GlobalValue::LinkOnceODRLinkage: 2589 case llvm::GlobalValue::WeakODRLinkage: 2590 case llvm::GlobalValue::InternalLinkage: 2591 case llvm::GlobalValue::PrivateLinkage: 2592 return true; 2593 default: 2594 return false; 2595 } 2596 } 2597 2598 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) { 2599 const NamedDecl *ND = E->getDecl(); 2600 QualType T = E->getType(); 2601 2602 assert(E->isNonOdrUse() != NOUR_Unevaluated && 2603 "should not emit an unevaluated operand"); 2604 2605 if (const auto *VD = dyn_cast<VarDecl>(ND)) { 2606 // Global Named registers access via intrinsics only 2607 if (VD->getStorageClass() == SC_Register && 2608 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl()) 2609 return EmitGlobalNamedRegister(VD, CGM); 2610 2611 // If this DeclRefExpr does not constitute an odr-use of the variable, 2612 // we're not permitted to emit a reference to it in general, and it might 2613 // not be captured if capture would be necessary for a use. Emit the 2614 // constant value directly instead. 2615 if (E->isNonOdrUse() == NOUR_Constant && 2616 (VD->getType()->isReferenceType() || 2617 !canEmitSpuriousReferenceToVariable(*this, E, VD, true))) { 2618 VD->getAnyInitializer(VD); 2619 llvm::Constant *Val = ConstantEmitter(*this).emitAbstract( 2620 E->getLocation(), *VD->evaluateValue(), VD->getType()); 2621 assert(Val && "failed to emit constant expression"); 2622 2623 Address Addr = Address::invalid(); 2624 if (!VD->getType()->isReferenceType()) { 2625 // Spill the constant value to a global. 2626 Addr = CGM.createUnnamedGlobalFrom(*VD, Val, 2627 getContext().getDeclAlign(VD)); 2628 llvm::Type *VarTy = getTypes().ConvertTypeForMem(VD->getType()); 2629 auto *PTy = llvm::PointerType::get( 2630 VarTy, getContext().getTargetAddressSpace(VD->getType())); 2631 if (PTy != Addr.getType()) 2632 Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy); 2633 } else { 2634 // Should we be using the alignment of the constant pointer we emitted? 2635 CharUnits Alignment = 2636 CGM.getNaturalTypeAlignment(E->getType(), 2637 /* BaseInfo= */ nullptr, 2638 /* TBAAInfo= */ nullptr, 2639 /* forPointeeType= */ true); 2640 Addr = Address(Val, Alignment); 2641 } 2642 return MakeAddrLValue(Addr, T, AlignmentSource::Decl); 2643 } 2644 2645 // FIXME: Handle other kinds of non-odr-use DeclRefExprs. 2646 2647 // Check for captured variables. 2648 if (E->refersToEnclosingVariableOrCapture()) { 2649 VD = VD->getCanonicalDecl(); 2650 if (auto *FD = LambdaCaptureFields.lookup(VD)) 2651 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue); 2652 if (CapturedStmtInfo) { 2653 auto I = LocalDeclMap.find(VD); 2654 if (I != LocalDeclMap.end()) { 2655 LValue CapLVal; 2656 if (VD->getType()->isReferenceType()) 2657 CapLVal = EmitLoadOfReferenceLValue(I->second, VD->getType(), 2658 AlignmentSource::Decl); 2659 else 2660 CapLVal = MakeAddrLValue(I->second, T); 2661 // Mark lvalue as nontemporal if the variable is marked as nontemporal 2662 // in simd context. 2663 if (getLangOpts().OpenMP && 2664 CGM.getOpenMPRuntime().isNontemporalDecl(VD)) 2665 CapLVal.setNontemporal(/*Value=*/true); 2666 return CapLVal; 2667 } 2668 LValue CapLVal = 2669 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD), 2670 CapturedStmtInfo->getContextValue()); 2671 CapLVal = MakeAddrLValue( 2672 Address(CapLVal.getPointer(*this), getContext().getDeclAlign(VD)), 2673 CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl), 2674 CapLVal.getTBAAInfo()); 2675 // Mark lvalue as nontemporal if the variable is marked as nontemporal 2676 // in simd context. 2677 if (getLangOpts().OpenMP && 2678 CGM.getOpenMPRuntime().isNontemporalDecl(VD)) 2679 CapLVal.setNontemporal(/*Value=*/true); 2680 return CapLVal; 2681 } 2682 2683 assert(isa<BlockDecl>(CurCodeDecl)); 2684 Address addr = GetAddrOfBlockDecl(VD); 2685 return MakeAddrLValue(addr, T, AlignmentSource::Decl); 2686 } 2687 } 2688 2689 // FIXME: We should be able to assert this for FunctionDecls as well! 2690 // FIXME: We should be able to assert this for all DeclRefExprs, not just 2691 // those with a valid source location. 2692 assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() || 2693 !E->getLocation().isValid()) && 2694 "Should not use decl without marking it used!"); 2695 2696 if (ND->hasAttr<WeakRefAttr>()) { 2697 const auto *VD = cast<ValueDecl>(ND); 2698 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD); 2699 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl); 2700 } 2701 2702 if (const auto *VD = dyn_cast<VarDecl>(ND)) { 2703 // Check if this is a global variable. 2704 if (VD->hasLinkage() || VD->isStaticDataMember()) 2705 return EmitGlobalVarDeclLValue(*this, E, VD); 2706 2707 Address addr = Address::invalid(); 2708 2709 // The variable should generally be present in the local decl map. 2710 auto iter = LocalDeclMap.find(VD); 2711 if (iter != LocalDeclMap.end()) { 2712 addr = iter->second; 2713 2714 // Otherwise, it might be static local we haven't emitted yet for 2715 // some reason; most likely, because it's in an outer function. 2716 } else if (VD->isStaticLocal()) { 2717 addr = Address(CGM.getOrCreateStaticVarDecl( 2718 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false)), 2719 getContext().getDeclAlign(VD)); 2720 2721 // No other cases for now. 2722 } else { 2723 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?"); 2724 } 2725 2726 2727 // Check for OpenMP threadprivate variables. 2728 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd && 2729 VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 2730 return EmitThreadPrivateVarDeclLValue( 2731 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()), 2732 E->getExprLoc()); 2733 } 2734 2735 // Drill into block byref variables. 2736 bool isBlockByref = VD->isEscapingByref(); 2737 if (isBlockByref) { 2738 addr = emitBlockByrefAddress(addr, VD); 2739 } 2740 2741 // Drill into reference types. 2742 LValue LV = VD->getType()->isReferenceType() ? 2743 EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) : 2744 MakeAddrLValue(addr, T, AlignmentSource::Decl); 2745 2746 bool isLocalStorage = VD->hasLocalStorage(); 2747 2748 bool NonGCable = isLocalStorage && 2749 !VD->getType()->isReferenceType() && 2750 !isBlockByref; 2751 if (NonGCable) { 2752 LV.getQuals().removeObjCGCAttr(); 2753 LV.setNonGC(true); 2754 } 2755 2756 bool isImpreciseLifetime = 2757 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>()); 2758 if (isImpreciseLifetime) 2759 LV.setARCPreciseLifetime(ARCImpreciseLifetime); 2760 setObjCGCLValueClass(getContext(), E, LV); 2761 return LV; 2762 } 2763 2764 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 2765 return EmitFunctionDeclLValue(*this, E, FD); 2766 2767 // FIXME: While we're emitting a binding from an enclosing scope, all other 2768 // DeclRefExprs we see should be implicitly treated as if they also refer to 2769 // an enclosing scope. 2770 if (const auto *BD = dyn_cast<BindingDecl>(ND)) 2771 return EmitLValue(BD->getBinding()); 2772 2773 // We can form DeclRefExprs naming GUID declarations when reconstituting 2774 // non-type template parameters into expressions. 2775 if (const auto *GD = dyn_cast<MSGuidDecl>(ND)) 2776 return MakeAddrLValue(CGM.GetAddrOfMSGuidDecl(GD), T, 2777 AlignmentSource::Decl); 2778 2779 llvm_unreachable("Unhandled DeclRefExpr"); 2780 } 2781 2782 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) { 2783 // __extension__ doesn't affect lvalue-ness. 2784 if (E->getOpcode() == UO_Extension) 2785 return EmitLValue(E->getSubExpr()); 2786 2787 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType()); 2788 switch (E->getOpcode()) { 2789 default: llvm_unreachable("Unknown unary operator lvalue!"); 2790 case UO_Deref: { 2791 QualType T = E->getSubExpr()->getType()->getPointeeType(); 2792 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type"); 2793 2794 LValueBaseInfo BaseInfo; 2795 TBAAAccessInfo TBAAInfo; 2796 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo, 2797 &TBAAInfo); 2798 LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo); 2799 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace()); 2800 2801 // We should not generate __weak write barrier on indirect reference 2802 // of a pointer to object; as in void foo (__weak id *param); *param = 0; 2803 // But, we continue to generate __strong write barrier on indirect write 2804 // into a pointer to object. 2805 if (getLangOpts().ObjC && 2806 getLangOpts().getGC() != LangOptions::NonGC && 2807 LV.isObjCWeak()) 2808 LV.setNonGC(!E->isOBJCGCCandidate(getContext())); 2809 return LV; 2810 } 2811 case UO_Real: 2812 case UO_Imag: { 2813 LValue LV = EmitLValue(E->getSubExpr()); 2814 assert(LV.isSimple() && "real/imag on non-ordinary l-value"); 2815 2816 // __real is valid on scalars. This is a faster way of testing that. 2817 // __imag can only produce an rvalue on scalars. 2818 if (E->getOpcode() == UO_Real && 2819 !LV.getAddress(*this).getElementType()->isStructTy()) { 2820 assert(E->getSubExpr()->getType()->isArithmeticType()); 2821 return LV; 2822 } 2823 2824 QualType T = ExprTy->castAs<ComplexType>()->getElementType(); 2825 2826 Address Component = 2827 (E->getOpcode() == UO_Real 2828 ? emitAddrOfRealComponent(LV.getAddress(*this), LV.getType()) 2829 : emitAddrOfImagComponent(LV.getAddress(*this), LV.getType())); 2830 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(), 2831 CGM.getTBAAInfoForSubobject(LV, T)); 2832 ElemLV.getQuals().addQualifiers(LV.getQuals()); 2833 return ElemLV; 2834 } 2835 case UO_PreInc: 2836 case UO_PreDec: { 2837 LValue LV = EmitLValue(E->getSubExpr()); 2838 bool isInc = E->getOpcode() == UO_PreInc; 2839 2840 if (E->getType()->isAnyComplexType()) 2841 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/); 2842 else 2843 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/); 2844 return LV; 2845 } 2846 } 2847 } 2848 2849 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) { 2850 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E), 2851 E->getType(), AlignmentSource::Decl); 2852 } 2853 2854 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) { 2855 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E), 2856 E->getType(), AlignmentSource::Decl); 2857 } 2858 2859 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) { 2860 auto SL = E->getFunctionName(); 2861 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr"); 2862 StringRef FnName = CurFn->getName(); 2863 if (FnName.startswith("\01")) 2864 FnName = FnName.substr(1); 2865 StringRef NameItems[] = { 2866 PredefinedExpr::getIdentKindName(E->getIdentKind()), FnName}; 2867 std::string GVName = llvm::join(NameItems, NameItems + 2, "."); 2868 if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) { 2869 std::string Name = std::string(SL->getString()); 2870 if (!Name.empty()) { 2871 unsigned Discriminator = 2872 CGM.getCXXABI().getMangleContext().getBlockId(BD, true); 2873 if (Discriminator) 2874 Name += "_" + Twine(Discriminator + 1).str(); 2875 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str()); 2876 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl); 2877 } else { 2878 auto C = 2879 CGM.GetAddrOfConstantCString(std::string(FnName), GVName.c_str()); 2880 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl); 2881 } 2882 } 2883 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName); 2884 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl); 2885 } 2886 2887 /// Emit a type description suitable for use by a runtime sanitizer library. The 2888 /// format of a type descriptor is 2889 /// 2890 /// \code 2891 /// { i16 TypeKind, i16 TypeInfo } 2892 /// \endcode 2893 /// 2894 /// followed by an array of i8 containing the type name. TypeKind is 0 for an 2895 /// integer, 1 for a floating point value, and -1 for anything else. 2896 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) { 2897 // Only emit each type's descriptor once. 2898 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T)) 2899 return C; 2900 2901 uint16_t TypeKind = -1; 2902 uint16_t TypeInfo = 0; 2903 2904 if (T->isIntegerType()) { 2905 TypeKind = 0; 2906 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) | 2907 (T->isSignedIntegerType() ? 1 : 0); 2908 } else if (T->isFloatingType()) { 2909 TypeKind = 1; 2910 TypeInfo = getContext().getTypeSize(T); 2911 } 2912 2913 // Format the type name as if for a diagnostic, including quotes and 2914 // optionally an 'aka'. 2915 SmallString<32> Buffer; 2916 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype, 2917 (intptr_t)T.getAsOpaquePtr(), 2918 StringRef(), StringRef(), None, Buffer, 2919 None); 2920 2921 llvm::Constant *Components[] = { 2922 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo), 2923 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer) 2924 }; 2925 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components); 2926 2927 auto *GV = new llvm::GlobalVariable( 2928 CGM.getModule(), Descriptor->getType(), 2929 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor); 2930 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2931 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV); 2932 2933 // Remember the descriptor for this type. 2934 CGM.setTypeDescriptorInMap(T, GV); 2935 2936 return GV; 2937 } 2938 2939 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) { 2940 llvm::Type *TargetTy = IntPtrTy; 2941 2942 if (V->getType() == TargetTy) 2943 return V; 2944 2945 // Floating-point types which fit into intptr_t are bitcast to integers 2946 // and then passed directly (after zero-extension, if necessary). 2947 if (V->getType()->isFloatingPointTy()) { 2948 unsigned Bits = V->getType()->getPrimitiveSizeInBits(); 2949 if (Bits <= TargetTy->getIntegerBitWidth()) 2950 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(), 2951 Bits)); 2952 } 2953 2954 // Integers which fit in intptr_t are zero-extended and passed directly. 2955 if (V->getType()->isIntegerTy() && 2956 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth()) 2957 return Builder.CreateZExt(V, TargetTy); 2958 2959 // Pointers are passed directly, everything else is passed by address. 2960 if (!V->getType()->isPointerTy()) { 2961 Address Ptr = CreateDefaultAlignTempAlloca(V->getType()); 2962 Builder.CreateStore(V, Ptr); 2963 V = Ptr.getPointer(); 2964 } 2965 return Builder.CreatePtrToInt(V, TargetTy); 2966 } 2967 2968 /// Emit a representation of a SourceLocation for passing to a handler 2969 /// in a sanitizer runtime library. The format for this data is: 2970 /// \code 2971 /// struct SourceLocation { 2972 /// const char *Filename; 2973 /// int32_t Line, Column; 2974 /// }; 2975 /// \endcode 2976 /// For an invalid SourceLocation, the Filename pointer is null. 2977 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) { 2978 llvm::Constant *Filename; 2979 int Line, Column; 2980 2981 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc); 2982 if (PLoc.isValid()) { 2983 StringRef FilenameString = PLoc.getFilename(); 2984 2985 int PathComponentsToStrip = 2986 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip; 2987 if (PathComponentsToStrip < 0) { 2988 assert(PathComponentsToStrip != INT_MIN); 2989 int PathComponentsToKeep = -PathComponentsToStrip; 2990 auto I = llvm::sys::path::rbegin(FilenameString); 2991 auto E = llvm::sys::path::rend(FilenameString); 2992 while (I != E && --PathComponentsToKeep) 2993 ++I; 2994 2995 FilenameString = FilenameString.substr(I - E); 2996 } else if (PathComponentsToStrip > 0) { 2997 auto I = llvm::sys::path::begin(FilenameString); 2998 auto E = llvm::sys::path::end(FilenameString); 2999 while (I != E && PathComponentsToStrip--) 3000 ++I; 3001 3002 if (I != E) 3003 FilenameString = 3004 FilenameString.substr(I - llvm::sys::path::begin(FilenameString)); 3005 else 3006 FilenameString = llvm::sys::path::filename(FilenameString); 3007 } 3008 3009 auto FilenameGV = 3010 CGM.GetAddrOfConstantCString(std::string(FilenameString), ".src"); 3011 CGM.getSanitizerMetadata()->disableSanitizerForGlobal( 3012 cast<llvm::GlobalVariable>(FilenameGV.getPointer())); 3013 Filename = FilenameGV.getPointer(); 3014 Line = PLoc.getLine(); 3015 Column = PLoc.getColumn(); 3016 } else { 3017 Filename = llvm::Constant::getNullValue(Int8PtrTy); 3018 Line = Column = 0; 3019 } 3020 3021 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line), 3022 Builder.getInt32(Column)}; 3023 3024 return llvm::ConstantStruct::getAnon(Data); 3025 } 3026 3027 namespace { 3028 /// Specify under what conditions this check can be recovered 3029 enum class CheckRecoverableKind { 3030 /// Always terminate program execution if this check fails. 3031 Unrecoverable, 3032 /// Check supports recovering, runtime has both fatal (noreturn) and 3033 /// non-fatal handlers for this check. 3034 Recoverable, 3035 /// Runtime conditionally aborts, always need to support recovery. 3036 AlwaysRecoverable 3037 }; 3038 } 3039 3040 static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) { 3041 assert(Kind.countPopulation() == 1); 3042 if (Kind == SanitizerKind::Function || Kind == SanitizerKind::Vptr) 3043 return CheckRecoverableKind::AlwaysRecoverable; 3044 else if (Kind == SanitizerKind::Return || Kind == SanitizerKind::Unreachable) 3045 return CheckRecoverableKind::Unrecoverable; 3046 else 3047 return CheckRecoverableKind::Recoverable; 3048 } 3049 3050 namespace { 3051 struct SanitizerHandlerInfo { 3052 char const *const Name; 3053 unsigned Version; 3054 }; 3055 } 3056 3057 const SanitizerHandlerInfo SanitizerHandlers[] = { 3058 #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version}, 3059 LIST_SANITIZER_CHECKS 3060 #undef SANITIZER_CHECK 3061 }; 3062 3063 static void emitCheckHandlerCall(CodeGenFunction &CGF, 3064 llvm::FunctionType *FnType, 3065 ArrayRef<llvm::Value *> FnArgs, 3066 SanitizerHandler CheckHandler, 3067 CheckRecoverableKind RecoverKind, bool IsFatal, 3068 llvm::BasicBlock *ContBB) { 3069 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable); 3070 Optional<ApplyDebugLocation> DL; 3071 if (!CGF.Builder.getCurrentDebugLocation()) { 3072 // Ensure that the call has at least an artificial debug location. 3073 DL.emplace(CGF, SourceLocation()); 3074 } 3075 bool NeedsAbortSuffix = 3076 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable; 3077 bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime; 3078 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler]; 3079 const StringRef CheckName = CheckInfo.Name; 3080 std::string FnName = "__ubsan_handle_" + CheckName.str(); 3081 if (CheckInfo.Version && !MinimalRuntime) 3082 FnName += "_v" + llvm::utostr(CheckInfo.Version); 3083 if (MinimalRuntime) 3084 FnName += "_minimal"; 3085 if (NeedsAbortSuffix) 3086 FnName += "_abort"; 3087 bool MayReturn = 3088 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable; 3089 3090 llvm::AttrBuilder B; 3091 if (!MayReturn) { 3092 B.addAttribute(llvm::Attribute::NoReturn) 3093 .addAttribute(llvm::Attribute::NoUnwind); 3094 } 3095 B.addAttribute(llvm::Attribute::UWTable); 3096 3097 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction( 3098 FnType, FnName, 3099 llvm::AttributeList::get(CGF.getLLVMContext(), 3100 llvm::AttributeList::FunctionIndex, B), 3101 /*Local=*/true); 3102 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs); 3103 if (!MayReturn) { 3104 HandlerCall->setDoesNotReturn(); 3105 CGF.Builder.CreateUnreachable(); 3106 } else { 3107 CGF.Builder.CreateBr(ContBB); 3108 } 3109 } 3110 3111 void CodeGenFunction::EmitCheck( 3112 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked, 3113 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs, 3114 ArrayRef<llvm::Value *> DynamicArgs) { 3115 assert(IsSanitizerScope); 3116 assert(Checked.size() > 0); 3117 assert(CheckHandler >= 0 && 3118 size_t(CheckHandler) < llvm::array_lengthof(SanitizerHandlers)); 3119 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name; 3120 3121 llvm::Value *FatalCond = nullptr; 3122 llvm::Value *RecoverableCond = nullptr; 3123 llvm::Value *TrapCond = nullptr; 3124 for (int i = 0, n = Checked.size(); i < n; ++i) { 3125 llvm::Value *Check = Checked[i].first; 3126 // -fsanitize-trap= overrides -fsanitize-recover=. 3127 llvm::Value *&Cond = 3128 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second) 3129 ? TrapCond 3130 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second) 3131 ? RecoverableCond 3132 : FatalCond; 3133 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check; 3134 } 3135 3136 if (TrapCond) 3137 EmitTrapCheck(TrapCond); 3138 if (!FatalCond && !RecoverableCond) 3139 return; 3140 3141 llvm::Value *JointCond; 3142 if (FatalCond && RecoverableCond) 3143 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond); 3144 else 3145 JointCond = FatalCond ? FatalCond : RecoverableCond; 3146 assert(JointCond); 3147 3148 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second); 3149 assert(SanOpts.has(Checked[0].second)); 3150 #ifndef NDEBUG 3151 for (int i = 1, n = Checked.size(); i < n; ++i) { 3152 assert(RecoverKind == getRecoverableKind(Checked[i].second) && 3153 "All recoverable kinds in a single check must be same!"); 3154 assert(SanOpts.has(Checked[i].second)); 3155 } 3156 #endif 3157 3158 llvm::BasicBlock *Cont = createBasicBlock("cont"); 3159 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName); 3160 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers); 3161 // Give hint that we very much don't expect to execute the handler 3162 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp 3163 llvm::MDBuilder MDHelper(getLLVMContext()); 3164 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1); 3165 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node); 3166 EmitBlock(Handlers); 3167 3168 // Handler functions take an i8* pointing to the (handler-specific) static 3169 // information block, followed by a sequence of intptr_t arguments 3170 // representing operand values. 3171 SmallVector<llvm::Value *, 4> Args; 3172 SmallVector<llvm::Type *, 4> ArgTypes; 3173 if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) { 3174 Args.reserve(DynamicArgs.size() + 1); 3175 ArgTypes.reserve(DynamicArgs.size() + 1); 3176 3177 // Emit handler arguments and create handler function type. 3178 if (!StaticArgs.empty()) { 3179 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs); 3180 auto *InfoPtr = 3181 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false, 3182 llvm::GlobalVariable::PrivateLinkage, Info); 3183 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3184 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr); 3185 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy)); 3186 ArgTypes.push_back(Int8PtrTy); 3187 } 3188 3189 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) { 3190 Args.push_back(EmitCheckValue(DynamicArgs[i])); 3191 ArgTypes.push_back(IntPtrTy); 3192 } 3193 } 3194 3195 llvm::FunctionType *FnType = 3196 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false); 3197 3198 if (!FatalCond || !RecoverableCond) { 3199 // Simple case: we need to generate a single handler call, either 3200 // fatal, or non-fatal. 3201 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, 3202 (FatalCond != nullptr), Cont); 3203 } else { 3204 // Emit two handler calls: first one for set of unrecoverable checks, 3205 // another one for recoverable. 3206 llvm::BasicBlock *NonFatalHandlerBB = 3207 createBasicBlock("non_fatal." + CheckName); 3208 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName); 3209 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB); 3210 EmitBlock(FatalHandlerBB); 3211 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true, 3212 NonFatalHandlerBB); 3213 EmitBlock(NonFatalHandlerBB); 3214 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false, 3215 Cont); 3216 } 3217 3218 EmitBlock(Cont); 3219 } 3220 3221 void CodeGenFunction::EmitCfiSlowPathCheck( 3222 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId, 3223 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) { 3224 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont"); 3225 3226 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath"); 3227 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB); 3228 3229 llvm::MDBuilder MDHelper(getLLVMContext()); 3230 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1); 3231 BI->setMetadata(llvm::LLVMContext::MD_prof, Node); 3232 3233 EmitBlock(CheckBB); 3234 3235 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind); 3236 3237 llvm::CallInst *CheckCall; 3238 llvm::FunctionCallee SlowPathFn; 3239 if (WithDiag) { 3240 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs); 3241 auto *InfoPtr = 3242 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false, 3243 llvm::GlobalVariable::PrivateLinkage, Info); 3244 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3245 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr); 3246 3247 SlowPathFn = CGM.getModule().getOrInsertFunction( 3248 "__cfi_slowpath_diag", 3249 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, 3250 false)); 3251 CheckCall = Builder.CreateCall( 3252 SlowPathFn, {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)}); 3253 } else { 3254 SlowPathFn = CGM.getModule().getOrInsertFunction( 3255 "__cfi_slowpath", 3256 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false)); 3257 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr}); 3258 } 3259 3260 CGM.setDSOLocal( 3261 cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts())); 3262 CheckCall->setDoesNotThrow(); 3263 3264 EmitBlock(Cont); 3265 } 3266 3267 // Emit a stub for __cfi_check function so that the linker knows about this 3268 // symbol in LTO mode. 3269 void CodeGenFunction::EmitCfiCheckStub() { 3270 llvm::Module *M = &CGM.getModule(); 3271 auto &Ctx = M->getContext(); 3272 llvm::Function *F = llvm::Function::Create( 3273 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false), 3274 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M); 3275 CGM.setDSOLocal(F); 3276 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F); 3277 // FIXME: consider emitting an intrinsic call like 3278 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2) 3279 // which can be lowered in CrossDSOCFI pass to the actual contents of 3280 // __cfi_check. This would allow inlining of __cfi_check calls. 3281 llvm::CallInst::Create( 3282 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB); 3283 llvm::ReturnInst::Create(Ctx, nullptr, BB); 3284 } 3285 3286 // This function is basically a switch over the CFI failure kind, which is 3287 // extracted from CFICheckFailData (1st function argument). Each case is either 3288 // llvm.trap or a call to one of the two runtime handlers, based on 3289 // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid 3290 // failure kind) traps, but this should really never happen. CFICheckFailData 3291 // can be nullptr if the calling module has -fsanitize-trap behavior for this 3292 // check kind; in this case __cfi_check_fail traps as well. 3293 void CodeGenFunction::EmitCfiCheckFail() { 3294 SanitizerScope SanScope(this); 3295 FunctionArgList Args; 3296 ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy, 3297 ImplicitParamDecl::Other); 3298 ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy, 3299 ImplicitParamDecl::Other); 3300 Args.push_back(&ArgData); 3301 Args.push_back(&ArgAddr); 3302 3303 const CGFunctionInfo &FI = 3304 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args); 3305 3306 llvm::Function *F = llvm::Function::Create( 3307 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false), 3308 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule()); 3309 3310 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F); 3311 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F); 3312 F->setVisibility(llvm::GlobalValue::HiddenVisibility); 3313 3314 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args, 3315 SourceLocation()); 3316 3317 // This function should not be affected by blacklist. This function does 3318 // not have a source location, but "src:*" would still apply. Revert any 3319 // changes to SanOpts made in StartFunction. 3320 SanOpts = CGM.getLangOpts().Sanitize; 3321 3322 llvm::Value *Data = 3323 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false, 3324 CGM.getContext().VoidPtrTy, ArgData.getLocation()); 3325 llvm::Value *Addr = 3326 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false, 3327 CGM.getContext().VoidPtrTy, ArgAddr.getLocation()); 3328 3329 // Data == nullptr means the calling module has trap behaviour for this check. 3330 llvm::Value *DataIsNotNullPtr = 3331 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy)); 3332 EmitTrapCheck(DataIsNotNullPtr); 3333 3334 llvm::StructType *SourceLocationTy = 3335 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty); 3336 llvm::StructType *CfiCheckFailDataTy = 3337 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy); 3338 3339 llvm::Value *V = Builder.CreateConstGEP2_32( 3340 CfiCheckFailDataTy, 3341 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0, 3342 0); 3343 Address CheckKindAddr(V, getIntAlign()); 3344 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr); 3345 3346 llvm::Value *AllVtables = llvm::MetadataAsValue::get( 3347 CGM.getLLVMContext(), 3348 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables")); 3349 llvm::Value *ValidVtable = Builder.CreateZExt( 3350 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test), 3351 {Addr, AllVtables}), 3352 IntPtrTy); 3353 3354 const std::pair<int, SanitizerMask> CheckKinds[] = { 3355 {CFITCK_VCall, SanitizerKind::CFIVCall}, 3356 {CFITCK_NVCall, SanitizerKind::CFINVCall}, 3357 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast}, 3358 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast}, 3359 {CFITCK_ICall, SanitizerKind::CFIICall}}; 3360 3361 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks; 3362 for (auto CheckKindMaskPair : CheckKinds) { 3363 int Kind = CheckKindMaskPair.first; 3364 SanitizerMask Mask = CheckKindMaskPair.second; 3365 llvm::Value *Cond = 3366 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind)); 3367 if (CGM.getLangOpts().Sanitize.has(Mask)) 3368 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {}, 3369 {Data, Addr, ValidVtable}); 3370 else 3371 EmitTrapCheck(Cond); 3372 } 3373 3374 FinishFunction(); 3375 // The only reference to this function will be created during LTO link. 3376 // Make sure it survives until then. 3377 CGM.addUsedGlobal(F); 3378 } 3379 3380 void CodeGenFunction::EmitUnreachable(SourceLocation Loc) { 3381 if (SanOpts.has(SanitizerKind::Unreachable)) { 3382 SanitizerScope SanScope(this); 3383 EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()), 3384 SanitizerKind::Unreachable), 3385 SanitizerHandler::BuiltinUnreachable, 3386 EmitCheckSourceLocation(Loc), None); 3387 } 3388 Builder.CreateUnreachable(); 3389 } 3390 3391 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) { 3392 llvm::BasicBlock *Cont = createBasicBlock("cont"); 3393 3394 // If we're optimizing, collapse all calls to trap down to just one per 3395 // function to save on code size. 3396 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) { 3397 TrapBB = createBasicBlock("trap"); 3398 Builder.CreateCondBr(Checked, Cont, TrapBB); 3399 EmitBlock(TrapBB); 3400 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap); 3401 TrapCall->setDoesNotReturn(); 3402 TrapCall->setDoesNotThrow(); 3403 Builder.CreateUnreachable(); 3404 } else { 3405 Builder.CreateCondBr(Checked, Cont, TrapBB); 3406 } 3407 3408 EmitBlock(Cont); 3409 } 3410 3411 llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) { 3412 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID)); 3413 3414 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) { 3415 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name", 3416 CGM.getCodeGenOpts().TrapFuncName); 3417 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A); 3418 } 3419 3420 return TrapCall; 3421 } 3422 3423 Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E, 3424 LValueBaseInfo *BaseInfo, 3425 TBAAAccessInfo *TBAAInfo) { 3426 assert(E->getType()->isArrayType() && 3427 "Array to pointer decay must have array source type!"); 3428 3429 // Expressions of array type can't be bitfields or vector elements. 3430 LValue LV = EmitLValue(E); 3431 Address Addr = LV.getAddress(*this); 3432 3433 // If the array type was an incomplete type, we need to make sure 3434 // the decay ends up being the right type. 3435 llvm::Type *NewTy = ConvertType(E->getType()); 3436 Addr = Builder.CreateElementBitCast(Addr, NewTy); 3437 3438 // Note that VLA pointers are always decayed, so we don't need to do 3439 // anything here. 3440 if (!E->getType()->isVariableArrayType()) { 3441 assert(isa<llvm::ArrayType>(Addr.getElementType()) && 3442 "Expected pointer to array"); 3443 Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay"); 3444 } 3445 3446 // The result of this decay conversion points to an array element within the 3447 // base lvalue. However, since TBAA currently does not support representing 3448 // accesses to elements of member arrays, we conservatively represent accesses 3449 // to the pointee object as if it had no any base lvalue specified. 3450 // TODO: Support TBAA for member arrays. 3451 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType(); 3452 if (BaseInfo) *BaseInfo = LV.getBaseInfo(); 3453 if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType); 3454 3455 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType)); 3456 } 3457 3458 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an 3459 /// array to pointer, return the array subexpression. 3460 static const Expr *isSimpleArrayDecayOperand(const Expr *E) { 3461 // If this isn't just an array->pointer decay, bail out. 3462 const auto *CE = dyn_cast<CastExpr>(E); 3463 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay) 3464 return nullptr; 3465 3466 // If this is a decay from variable width array, bail out. 3467 const Expr *SubExpr = CE->getSubExpr(); 3468 if (SubExpr->getType()->isVariableArrayType()) 3469 return nullptr; 3470 3471 return SubExpr; 3472 } 3473 3474 static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF, 3475 llvm::Value *ptr, 3476 ArrayRef<llvm::Value*> indices, 3477 bool inbounds, 3478 bool signedIndices, 3479 SourceLocation loc, 3480 const llvm::Twine &name = "arrayidx") { 3481 if (inbounds) { 3482 return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices, 3483 CodeGenFunction::NotSubtraction, loc, 3484 name); 3485 } else { 3486 return CGF.Builder.CreateGEP(ptr, indices, name); 3487 } 3488 } 3489 3490 static CharUnits getArrayElementAlign(CharUnits arrayAlign, 3491 llvm::Value *idx, 3492 CharUnits eltSize) { 3493 // If we have a constant index, we can use the exact offset of the 3494 // element we're accessing. 3495 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) { 3496 CharUnits offset = constantIdx->getZExtValue() * eltSize; 3497 return arrayAlign.alignmentAtOffset(offset); 3498 3499 // Otherwise, use the worst-case alignment for any element. 3500 } else { 3501 return arrayAlign.alignmentOfArrayElement(eltSize); 3502 } 3503 } 3504 3505 static QualType getFixedSizeElementType(const ASTContext &ctx, 3506 const VariableArrayType *vla) { 3507 QualType eltType; 3508 do { 3509 eltType = vla->getElementType(); 3510 } while ((vla = ctx.getAsVariableArrayType(eltType))); 3511 return eltType; 3512 } 3513 3514 /// Given an array base, check whether its member access belongs to a record 3515 /// with preserve_access_index attribute or not. 3516 static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase) { 3517 if (!ArrayBase || !CGF.getDebugInfo()) 3518 return false; 3519 3520 // Only support base as either a MemberExpr or DeclRefExpr. 3521 // DeclRefExpr to cover cases like: 3522 // struct s { int a; int b[10]; }; 3523 // struct s *p; 3524 // p[1].a 3525 // p[1] will generate a DeclRefExpr and p[1].a is a MemberExpr. 3526 // p->b[5] is a MemberExpr example. 3527 const Expr *E = ArrayBase->IgnoreImpCasts(); 3528 if (const auto *ME = dyn_cast<MemberExpr>(E)) 3529 return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>(); 3530 3531 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) { 3532 const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl()); 3533 if (!VarDef) 3534 return false; 3535 3536 const auto *PtrT = VarDef->getType()->getAs<PointerType>(); 3537 if (!PtrT) 3538 return false; 3539 3540 const auto *PointeeT = PtrT->getPointeeType() 3541 ->getUnqualifiedDesugaredType(); 3542 if (const auto *RecT = dyn_cast<RecordType>(PointeeT)) 3543 return RecT->getDecl()->hasAttr<BPFPreserveAccessIndexAttr>(); 3544 return false; 3545 } 3546 3547 return false; 3548 } 3549 3550 static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr, 3551 ArrayRef<llvm::Value *> indices, 3552 QualType eltType, bool inbounds, 3553 bool signedIndices, SourceLocation loc, 3554 QualType *arrayType = nullptr, 3555 const Expr *Base = nullptr, 3556 const llvm::Twine &name = "arrayidx") { 3557 // All the indices except that last must be zero. 3558 #ifndef NDEBUG 3559 for (auto idx : indices.drop_back()) 3560 assert(isa<llvm::ConstantInt>(idx) && 3561 cast<llvm::ConstantInt>(idx)->isZero()); 3562 #endif 3563 3564 // Determine the element size of the statically-sized base. This is 3565 // the thing that the indices are expressed in terms of. 3566 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) { 3567 eltType = getFixedSizeElementType(CGF.getContext(), vla); 3568 } 3569 3570 // We can use that to compute the best alignment of the element. 3571 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType); 3572 CharUnits eltAlign = 3573 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize); 3574 3575 llvm::Value *eltPtr; 3576 auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back()); 3577 if (!LastIndex || 3578 (!CGF.IsInPreservedAIRegion && !IsPreserveAIArrayBase(CGF, Base))) { 3579 eltPtr = emitArraySubscriptGEP( 3580 CGF, addr.getPointer(), indices, inbounds, signedIndices, 3581 loc, name); 3582 } else { 3583 // Remember the original array subscript for bpf target 3584 unsigned idx = LastIndex->getZExtValue(); 3585 llvm::DIType *DbgInfo = nullptr; 3586 if (arrayType) 3587 DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(*arrayType, loc); 3588 eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex(addr.getElementType(), 3589 addr.getPointer(), 3590 indices.size() - 1, 3591 idx, DbgInfo); 3592 } 3593 3594 return Address(eltPtr, eltAlign); 3595 } 3596 3597 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E, 3598 bool Accessed) { 3599 // The index must always be an integer, which is not an aggregate. Emit it 3600 // in lexical order (this complexity is, sadly, required by C++17). 3601 llvm::Value *IdxPre = 3602 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr; 3603 bool SignedIndices = false; 3604 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * { 3605 auto *Idx = IdxPre; 3606 if (E->getLHS() != E->getIdx()) { 3607 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS"); 3608 Idx = EmitScalarExpr(E->getIdx()); 3609 } 3610 3611 QualType IdxTy = E->getIdx()->getType(); 3612 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType(); 3613 SignedIndices |= IdxSigned; 3614 3615 if (SanOpts.has(SanitizerKind::ArrayBounds)) 3616 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed); 3617 3618 // Extend or truncate the index type to 32 or 64-bits. 3619 if (Promote && Idx->getType() != IntPtrTy) 3620 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom"); 3621 3622 return Idx; 3623 }; 3624 IdxPre = nullptr; 3625 3626 // If the base is a vector type, then we are forming a vector element lvalue 3627 // with this subscript. 3628 if (E->getBase()->getType()->isVectorType() && 3629 !isa<ExtVectorElementExpr>(E->getBase())) { 3630 // Emit the vector as an lvalue to get its address. 3631 LValue LHS = EmitLValue(E->getBase()); 3632 auto *Idx = EmitIdxAfterBase(/*Promote*/false); 3633 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!"); 3634 return LValue::MakeVectorElt(LHS.getAddress(*this), Idx, 3635 E->getBase()->getType(), LHS.getBaseInfo(), 3636 TBAAAccessInfo()); 3637 } 3638 3639 // All the other cases basically behave like simple offsetting. 3640 3641 // Handle the extvector case we ignored above. 3642 if (isa<ExtVectorElementExpr>(E->getBase())) { 3643 LValue LV = EmitLValue(E->getBase()); 3644 auto *Idx = EmitIdxAfterBase(/*Promote*/true); 3645 Address Addr = EmitExtVectorElementLValue(LV); 3646 3647 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType(); 3648 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true, 3649 SignedIndices, E->getExprLoc()); 3650 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(), 3651 CGM.getTBAAInfoForSubobject(LV, EltType)); 3652 } 3653 3654 LValueBaseInfo EltBaseInfo; 3655 TBAAAccessInfo EltTBAAInfo; 3656 Address Addr = Address::invalid(); 3657 if (const VariableArrayType *vla = 3658 getContext().getAsVariableArrayType(E->getType())) { 3659 // The base must be a pointer, which is not an aggregate. Emit 3660 // it. It needs to be emitted first in case it's what captures 3661 // the VLA bounds. 3662 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo); 3663 auto *Idx = EmitIdxAfterBase(/*Promote*/true); 3664 3665 // The element count here is the total number of non-VLA elements. 3666 llvm::Value *numElements = getVLASize(vla).NumElts; 3667 3668 // Effectively, the multiply by the VLA size is part of the GEP. 3669 // GEP indexes are signed, and scaling an index isn't permitted to 3670 // signed-overflow, so we use the same semantics for our explicit 3671 // multiply. We suppress this if overflow is not undefined behavior. 3672 if (getLangOpts().isSignedOverflowDefined()) { 3673 Idx = Builder.CreateMul(Idx, numElements); 3674 } else { 3675 Idx = Builder.CreateNSWMul(Idx, numElements); 3676 } 3677 3678 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(), 3679 !getLangOpts().isSignedOverflowDefined(), 3680 SignedIndices, E->getExprLoc()); 3681 3682 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){ 3683 // Indexing over an interface, as in "NSString *P; P[4];" 3684 3685 // Emit the base pointer. 3686 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo); 3687 auto *Idx = EmitIdxAfterBase(/*Promote*/true); 3688 3689 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT); 3690 llvm::Value *InterfaceSizeVal = 3691 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity()); 3692 3693 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal); 3694 3695 // We don't necessarily build correct LLVM struct types for ObjC 3696 // interfaces, so we can't rely on GEP to do this scaling 3697 // correctly, so we need to cast to i8*. FIXME: is this actually 3698 // true? A lot of other things in the fragile ABI would break... 3699 llvm::Type *OrigBaseTy = Addr.getType(); 3700 Addr = Builder.CreateElementBitCast(Addr, Int8Ty); 3701 3702 // Do the GEP. 3703 CharUnits EltAlign = 3704 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize); 3705 llvm::Value *EltPtr = 3706 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false, 3707 SignedIndices, E->getExprLoc()); 3708 Addr = Address(EltPtr, EltAlign); 3709 3710 // Cast back. 3711 Addr = Builder.CreateBitCast(Addr, OrigBaseTy); 3712 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) { 3713 // If this is A[i] where A is an array, the frontend will have decayed the 3714 // base to be a ArrayToPointerDecay implicit cast. While correct, it is 3715 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a 3716 // "gep x, i" here. Emit one "gep A, 0, i". 3717 assert(Array->getType()->isArrayType() && 3718 "Array to pointer decay must have array source type!"); 3719 LValue ArrayLV; 3720 // For simple multidimensional array indexing, set the 'accessed' flag for 3721 // better bounds-checking of the base expression. 3722 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array)) 3723 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true); 3724 else 3725 ArrayLV = EmitLValue(Array); 3726 auto *Idx = EmitIdxAfterBase(/*Promote*/true); 3727 3728 // Propagate the alignment from the array itself to the result. 3729 QualType arrayType = Array->getType(); 3730 Addr = emitArraySubscriptGEP( 3731 *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx}, 3732 E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices, 3733 E->getExprLoc(), &arrayType, E->getBase()); 3734 EltBaseInfo = ArrayLV.getBaseInfo(); 3735 EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType()); 3736 } else { 3737 // The base must be a pointer; emit it with an estimate of its alignment. 3738 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo); 3739 auto *Idx = EmitIdxAfterBase(/*Promote*/true); 3740 QualType ptrType = E->getBase()->getType(); 3741 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(), 3742 !getLangOpts().isSignedOverflowDefined(), 3743 SignedIndices, E->getExprLoc(), &ptrType, 3744 E->getBase()); 3745 } 3746 3747 LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo); 3748 3749 if (getLangOpts().ObjC && 3750 getLangOpts().getGC() != LangOptions::NonGC) { 3751 LV.setNonGC(!E->isOBJCGCCandidate(getContext())); 3752 setObjCGCLValueClass(getContext(), E, LV); 3753 } 3754 return LV; 3755 } 3756 3757 static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base, 3758 LValueBaseInfo &BaseInfo, 3759 TBAAAccessInfo &TBAAInfo, 3760 QualType BaseTy, QualType ElTy, 3761 bool IsLowerBound) { 3762 LValue BaseLVal; 3763 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) { 3764 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound); 3765 if (BaseTy->isArrayType()) { 3766 Address Addr = BaseLVal.getAddress(CGF); 3767 BaseInfo = BaseLVal.getBaseInfo(); 3768 3769 // If the array type was an incomplete type, we need to make sure 3770 // the decay ends up being the right type. 3771 llvm::Type *NewTy = CGF.ConvertType(BaseTy); 3772 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy); 3773 3774 // Note that VLA pointers are always decayed, so we don't need to do 3775 // anything here. 3776 if (!BaseTy->isVariableArrayType()) { 3777 assert(isa<llvm::ArrayType>(Addr.getElementType()) && 3778 "Expected pointer to array"); 3779 Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay"); 3780 } 3781 3782 return CGF.Builder.CreateElementBitCast(Addr, 3783 CGF.ConvertTypeForMem(ElTy)); 3784 } 3785 LValueBaseInfo TypeBaseInfo; 3786 TBAAAccessInfo TypeTBAAInfo; 3787 CharUnits Align = 3788 CGF.CGM.getNaturalTypeAlignment(ElTy, &TypeBaseInfo, &TypeTBAAInfo); 3789 BaseInfo.mergeForCast(TypeBaseInfo); 3790 TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo); 3791 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress(CGF)), Align); 3792 } 3793 return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo); 3794 } 3795 3796 LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E, 3797 bool IsLowerBound) { 3798 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase()); 3799 QualType ResultExprTy; 3800 if (auto *AT = getContext().getAsArrayType(BaseTy)) 3801 ResultExprTy = AT->getElementType(); 3802 else 3803 ResultExprTy = BaseTy->getPointeeType(); 3804 llvm::Value *Idx = nullptr; 3805 if (IsLowerBound || E->getColonLoc().isInvalid()) { 3806 // Requesting lower bound or upper bound, but without provided length and 3807 // without ':' symbol for the default length -> length = 1. 3808 // Idx = LowerBound ?: 0; 3809 if (auto *LowerBound = E->getLowerBound()) { 3810 Idx = Builder.CreateIntCast( 3811 EmitScalarExpr(LowerBound), IntPtrTy, 3812 LowerBound->getType()->hasSignedIntegerRepresentation()); 3813 } else 3814 Idx = llvm::ConstantInt::getNullValue(IntPtrTy); 3815 } else { 3816 // Try to emit length or lower bound as constant. If this is possible, 1 3817 // is subtracted from constant length or lower bound. Otherwise, emit LLVM 3818 // IR (LB + Len) - 1. 3819 auto &C = CGM.getContext(); 3820 auto *Length = E->getLength(); 3821 llvm::APSInt ConstLength; 3822 if (Length) { 3823 // Idx = LowerBound + Length - 1; 3824 if (Length->isIntegerConstantExpr(ConstLength, C)) { 3825 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits); 3826 Length = nullptr; 3827 } 3828 auto *LowerBound = E->getLowerBound(); 3829 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false); 3830 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) { 3831 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits); 3832 LowerBound = nullptr; 3833 } 3834 if (!Length) 3835 --ConstLength; 3836 else if (!LowerBound) 3837 --ConstLowerBound; 3838 3839 if (Length || LowerBound) { 3840 auto *LowerBoundVal = 3841 LowerBound 3842 ? Builder.CreateIntCast( 3843 EmitScalarExpr(LowerBound), IntPtrTy, 3844 LowerBound->getType()->hasSignedIntegerRepresentation()) 3845 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound); 3846 auto *LengthVal = 3847 Length 3848 ? Builder.CreateIntCast( 3849 EmitScalarExpr(Length), IntPtrTy, 3850 Length->getType()->hasSignedIntegerRepresentation()) 3851 : llvm::ConstantInt::get(IntPtrTy, ConstLength); 3852 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len", 3853 /*HasNUW=*/false, 3854 !getLangOpts().isSignedOverflowDefined()); 3855 if (Length && LowerBound) { 3856 Idx = Builder.CreateSub( 3857 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1", 3858 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined()); 3859 } 3860 } else 3861 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound); 3862 } else { 3863 // Idx = ArraySize - 1; 3864 QualType ArrayTy = BaseTy->isPointerType() 3865 ? E->getBase()->IgnoreParenImpCasts()->getType() 3866 : BaseTy; 3867 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) { 3868 Length = VAT->getSizeExpr(); 3869 if (Length->isIntegerConstantExpr(ConstLength, C)) 3870 Length = nullptr; 3871 } else { 3872 auto *CAT = C.getAsConstantArrayType(ArrayTy); 3873 ConstLength = CAT->getSize(); 3874 } 3875 if (Length) { 3876 auto *LengthVal = Builder.CreateIntCast( 3877 EmitScalarExpr(Length), IntPtrTy, 3878 Length->getType()->hasSignedIntegerRepresentation()); 3879 Idx = Builder.CreateSub( 3880 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1", 3881 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined()); 3882 } else { 3883 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits); 3884 --ConstLength; 3885 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength); 3886 } 3887 } 3888 } 3889 assert(Idx); 3890 3891 Address EltPtr = Address::invalid(); 3892 LValueBaseInfo BaseInfo; 3893 TBAAAccessInfo TBAAInfo; 3894 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) { 3895 // The base must be a pointer, which is not an aggregate. Emit 3896 // it. It needs to be emitted first in case it's what captures 3897 // the VLA bounds. 3898 Address Base = 3899 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo, 3900 BaseTy, VLA->getElementType(), IsLowerBound); 3901 // The element count here is the total number of non-VLA elements. 3902 llvm::Value *NumElements = getVLASize(VLA).NumElts; 3903 3904 // Effectively, the multiply by the VLA size is part of the GEP. 3905 // GEP indexes are signed, and scaling an index isn't permitted to 3906 // signed-overflow, so we use the same semantics for our explicit 3907 // multiply. We suppress this if overflow is not undefined behavior. 3908 if (getLangOpts().isSignedOverflowDefined()) 3909 Idx = Builder.CreateMul(Idx, NumElements); 3910 else 3911 Idx = Builder.CreateNSWMul(Idx, NumElements); 3912 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(), 3913 !getLangOpts().isSignedOverflowDefined(), 3914 /*signedIndices=*/false, E->getExprLoc()); 3915 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) { 3916 // If this is A[i] where A is an array, the frontend will have decayed the 3917 // base to be a ArrayToPointerDecay implicit cast. While correct, it is 3918 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a 3919 // "gep x, i" here. Emit one "gep A, 0, i". 3920 assert(Array->getType()->isArrayType() && 3921 "Array to pointer decay must have array source type!"); 3922 LValue ArrayLV; 3923 // For simple multidimensional array indexing, set the 'accessed' flag for 3924 // better bounds-checking of the base expression. 3925 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array)) 3926 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true); 3927 else 3928 ArrayLV = EmitLValue(Array); 3929 3930 // Propagate the alignment from the array itself to the result. 3931 EltPtr = emitArraySubscriptGEP( 3932 *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx}, 3933 ResultExprTy, !getLangOpts().isSignedOverflowDefined(), 3934 /*signedIndices=*/false, E->getExprLoc()); 3935 BaseInfo = ArrayLV.getBaseInfo(); 3936 TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy); 3937 } else { 3938 Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, 3939 TBAAInfo, BaseTy, ResultExprTy, 3940 IsLowerBound); 3941 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy, 3942 !getLangOpts().isSignedOverflowDefined(), 3943 /*signedIndices=*/false, E->getExprLoc()); 3944 } 3945 3946 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo); 3947 } 3948 3949 LValue CodeGenFunction:: 3950 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) { 3951 // Emit the base vector as an l-value. 3952 LValue Base; 3953 3954 // ExtVectorElementExpr's base can either be a vector or pointer to vector. 3955 if (E->isArrow()) { 3956 // If it is a pointer to a vector, emit the address and form an lvalue with 3957 // it. 3958 LValueBaseInfo BaseInfo; 3959 TBAAAccessInfo TBAAInfo; 3960 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo); 3961 const auto *PT = E->getBase()->getType()->castAs<PointerType>(); 3962 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo); 3963 Base.getQuals().removeObjCGCAttr(); 3964 } else if (E->getBase()->isGLValue()) { 3965 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x), 3966 // emit the base as an lvalue. 3967 assert(E->getBase()->getType()->isVectorType()); 3968 Base = EmitLValue(E->getBase()); 3969 } else { 3970 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such. 3971 assert(E->getBase()->getType()->isVectorType() && 3972 "Result must be a vector"); 3973 llvm::Value *Vec = EmitScalarExpr(E->getBase()); 3974 3975 // Store the vector to memory (because LValue wants an address). 3976 Address VecMem = CreateMemTemp(E->getBase()->getType()); 3977 Builder.CreateStore(Vec, VecMem); 3978 Base = MakeAddrLValue(VecMem, E->getBase()->getType(), 3979 AlignmentSource::Decl); 3980 } 3981 3982 QualType type = 3983 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers()); 3984 3985 // Encode the element access list into a vector of unsigned indices. 3986 SmallVector<uint32_t, 4> Indices; 3987 E->getEncodedElementAccess(Indices); 3988 3989 if (Base.isSimple()) { 3990 llvm::Constant *CV = 3991 llvm::ConstantDataVector::get(getLLVMContext(), Indices); 3992 return LValue::MakeExtVectorElt(Base.getAddress(*this), CV, type, 3993 Base.getBaseInfo(), TBAAAccessInfo()); 3994 } 3995 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!"); 3996 3997 llvm::Constant *BaseElts = Base.getExtVectorElts(); 3998 SmallVector<llvm::Constant *, 4> CElts; 3999 4000 for (unsigned i = 0, e = Indices.size(); i != e; ++i) 4001 CElts.push_back(BaseElts->getAggregateElement(Indices[i])); 4002 llvm::Constant *CV = llvm::ConstantVector::get(CElts); 4003 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type, 4004 Base.getBaseInfo(), TBAAAccessInfo()); 4005 } 4006 4007 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) { 4008 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) { 4009 EmitIgnoredExpr(E->getBase()); 4010 return EmitDeclRefLValue(DRE); 4011 } 4012 4013 Expr *BaseExpr = E->getBase(); 4014 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 4015 LValue BaseLV; 4016 if (E->isArrow()) { 4017 LValueBaseInfo BaseInfo; 4018 TBAAAccessInfo TBAAInfo; 4019 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo); 4020 QualType PtrTy = BaseExpr->getType()->getPointeeType(); 4021 SanitizerSet SkippedChecks; 4022 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr); 4023 if (IsBaseCXXThis) 4024 SkippedChecks.set(SanitizerKind::Alignment, true); 4025 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr)) 4026 SkippedChecks.set(SanitizerKind::Null, true); 4027 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy, 4028 /*Alignment=*/CharUnits::Zero(), SkippedChecks); 4029 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo); 4030 } else 4031 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess); 4032 4033 NamedDecl *ND = E->getMemberDecl(); 4034 if (auto *Field = dyn_cast<FieldDecl>(ND)) { 4035 LValue LV = EmitLValueForField(BaseLV, Field); 4036 setObjCGCLValueClass(getContext(), E, LV); 4037 if (getLangOpts().OpenMP) { 4038 // If the member was explicitly marked as nontemporal, mark it as 4039 // nontemporal. If the base lvalue is marked as nontemporal, mark access 4040 // to children as nontemporal too. 4041 if ((IsWrappedCXXThis(BaseExpr) && 4042 CGM.getOpenMPRuntime().isNontemporalDecl(Field)) || 4043 BaseLV.isNontemporal()) 4044 LV.setNontemporal(/*Value=*/true); 4045 } 4046 return LV; 4047 } 4048 4049 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 4050 return EmitFunctionDeclLValue(*this, E, FD); 4051 4052 llvm_unreachable("Unhandled member declaration!"); 4053 } 4054 4055 /// Given that we are currently emitting a lambda, emit an l-value for 4056 /// one of its members. 4057 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) { 4058 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda()); 4059 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent()); 4060 QualType LambdaTagType = 4061 getContext().getTagDeclType(Field->getParent()); 4062 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType); 4063 return EmitLValueForField(LambdaLV, Field); 4064 } 4065 4066 /// Get the field index in the debug info. The debug info structure/union 4067 /// will ignore the unnamed bitfields. 4068 unsigned CodeGenFunction::getDebugInfoFIndex(const RecordDecl *Rec, 4069 unsigned FieldIndex) { 4070 unsigned I = 0, Skipped = 0; 4071 4072 for (auto F : Rec->getDefinition()->fields()) { 4073 if (I == FieldIndex) 4074 break; 4075 if (F->isUnnamedBitfield()) 4076 Skipped++; 4077 I++; 4078 } 4079 4080 return FieldIndex - Skipped; 4081 } 4082 4083 /// Get the address of a zero-sized field within a record. The resulting 4084 /// address doesn't necessarily have the right type. 4085 static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base, 4086 const FieldDecl *Field) { 4087 CharUnits Offset = CGF.getContext().toCharUnitsFromBits( 4088 CGF.getContext().getFieldOffset(Field)); 4089 if (Offset.isZero()) 4090 return Base; 4091 Base = CGF.Builder.CreateElementBitCast(Base, CGF.Int8Ty); 4092 return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset); 4093 } 4094 4095 /// Drill down to the storage of a field without walking into 4096 /// reference types. 4097 /// 4098 /// The resulting address doesn't necessarily have the right type. 4099 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base, 4100 const FieldDecl *field) { 4101 if (field->isZeroSize(CGF.getContext())) 4102 return emitAddrOfZeroSizeField(CGF, base, field); 4103 4104 const RecordDecl *rec = field->getParent(); 4105 4106 unsigned idx = 4107 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field); 4108 4109 return CGF.Builder.CreateStructGEP(base, idx, field->getName()); 4110 } 4111 4112 static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base, 4113 Address addr, const FieldDecl *field) { 4114 const RecordDecl *rec = field->getParent(); 4115 llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType( 4116 base.getType(), rec->getLocation()); 4117 4118 unsigned idx = 4119 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field); 4120 4121 return CGF.Builder.CreatePreserveStructAccessIndex( 4122 addr, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo); 4123 } 4124 4125 static bool hasAnyVptr(const QualType Type, const ASTContext &Context) { 4126 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl(); 4127 if (!RD) 4128 return false; 4129 4130 if (RD->isDynamicClass()) 4131 return true; 4132 4133 for (const auto &Base : RD->bases()) 4134 if (hasAnyVptr(Base.getType(), Context)) 4135 return true; 4136 4137 for (const FieldDecl *Field : RD->fields()) 4138 if (hasAnyVptr(Field->getType(), Context)) 4139 return true; 4140 4141 return false; 4142 } 4143 4144 LValue CodeGenFunction::EmitLValueForField(LValue base, 4145 const FieldDecl *field) { 4146 LValueBaseInfo BaseInfo = base.getBaseInfo(); 4147 4148 if (field->isBitField()) { 4149 const CGRecordLayout &RL = 4150 CGM.getTypes().getCGRecordLayout(field->getParent()); 4151 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field); 4152 Address Addr = base.getAddress(*this); 4153 unsigned Idx = RL.getLLVMFieldNo(field); 4154 const RecordDecl *rec = field->getParent(); 4155 if (!IsInPreservedAIRegion && 4156 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) { 4157 if (Idx != 0) 4158 // For structs, we GEP to the field that the record layout suggests. 4159 Addr = Builder.CreateStructGEP(Addr, Idx, field->getName()); 4160 } else { 4161 llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType( 4162 getContext().getRecordType(rec), rec->getLocation()); 4163 Addr = Builder.CreatePreserveStructAccessIndex(Addr, Idx, 4164 getDebugInfoFIndex(rec, field->getFieldIndex()), 4165 DbgInfo); 4166 } 4167 4168 // Get the access type. 4169 llvm::Type *FieldIntTy = 4170 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize); 4171 if (Addr.getElementType() != FieldIntTy) 4172 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy); 4173 4174 QualType fieldType = 4175 field->getType().withCVRQualifiers(base.getVRQualifiers()); 4176 // TODO: Support TBAA for bit fields. 4177 LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource()); 4178 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo, 4179 TBAAAccessInfo()); 4180 } 4181 4182 // Fields of may-alias structures are may-alias themselves. 4183 // FIXME: this should get propagated down through anonymous structs 4184 // and unions. 4185 QualType FieldType = field->getType(); 4186 const RecordDecl *rec = field->getParent(); 4187 AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource(); 4188 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource)); 4189 TBAAAccessInfo FieldTBAAInfo; 4190 if (base.getTBAAInfo().isMayAlias() || 4191 rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) { 4192 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo(); 4193 } else if (rec->isUnion()) { 4194 // TODO: Support TBAA for unions. 4195 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo(); 4196 } else { 4197 // If no base type been assigned for the base access, then try to generate 4198 // one for this base lvalue. 4199 FieldTBAAInfo = base.getTBAAInfo(); 4200 if (!FieldTBAAInfo.BaseType) { 4201 FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType()); 4202 assert(!FieldTBAAInfo.Offset && 4203 "Nonzero offset for an access with no base type!"); 4204 } 4205 4206 // Adjust offset to be relative to the base type. 4207 const ASTRecordLayout &Layout = 4208 getContext().getASTRecordLayout(field->getParent()); 4209 unsigned CharWidth = getContext().getCharWidth(); 4210 if (FieldTBAAInfo.BaseType) 4211 FieldTBAAInfo.Offset += 4212 Layout.getFieldOffset(field->getFieldIndex()) / CharWidth; 4213 4214 // Update the final access type and size. 4215 FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType); 4216 FieldTBAAInfo.Size = 4217 getContext().getTypeSizeInChars(FieldType).getQuantity(); 4218 } 4219 4220 Address addr = base.getAddress(*this); 4221 if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) { 4222 if (CGM.getCodeGenOpts().StrictVTablePointers && 4223 ClassDef->isDynamicClass()) { 4224 // Getting to any field of dynamic object requires stripping dynamic 4225 // information provided by invariant.group. This is because accessing 4226 // fields may leak the real address of dynamic object, which could result 4227 // in miscompilation when leaked pointer would be compared. 4228 auto *stripped = Builder.CreateStripInvariantGroup(addr.getPointer()); 4229 addr = Address(stripped, addr.getAlignment()); 4230 } 4231 } 4232 4233 unsigned RecordCVR = base.getVRQualifiers(); 4234 if (rec->isUnion()) { 4235 // For unions, there is no pointer adjustment. 4236 if (CGM.getCodeGenOpts().StrictVTablePointers && 4237 hasAnyVptr(FieldType, getContext())) 4238 // Because unions can easily skip invariant.barriers, we need to add 4239 // a barrier every time CXXRecord field with vptr is referenced. 4240 addr = Address(Builder.CreateLaunderInvariantGroup(addr.getPointer()), 4241 addr.getAlignment()); 4242 4243 if (IsInPreservedAIRegion || 4244 (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) { 4245 // Remember the original union field index 4246 llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(base.getType(), 4247 rec->getLocation()); 4248 addr = Address( 4249 Builder.CreatePreserveUnionAccessIndex( 4250 addr.getPointer(), getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo), 4251 addr.getAlignment()); 4252 } 4253 4254 if (FieldType->isReferenceType()) 4255 addr = Builder.CreateElementBitCast( 4256 addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName()); 4257 } else { 4258 if (!IsInPreservedAIRegion && 4259 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) 4260 // For structs, we GEP to the field that the record layout suggests. 4261 addr = emitAddrOfFieldStorage(*this, addr, field); 4262 else 4263 // Remember the original struct field index 4264 addr = emitPreserveStructAccess(*this, base, addr, field); 4265 } 4266 4267 // If this is a reference field, load the reference right now. 4268 if (FieldType->isReferenceType()) { 4269 LValue RefLVal = 4270 MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo); 4271 if (RecordCVR & Qualifiers::Volatile) 4272 RefLVal.getQuals().addVolatile(); 4273 addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo); 4274 4275 // Qualifiers on the struct don't apply to the referencee. 4276 RecordCVR = 0; 4277 FieldType = FieldType->getPointeeType(); 4278 } 4279 4280 // Make sure that the address is pointing to the right type. This is critical 4281 // for both unions and structs. A union needs a bitcast, a struct element 4282 // will need a bitcast if the LLVM type laid out doesn't match the desired 4283 // type. 4284 addr = Builder.CreateElementBitCast( 4285 addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName()); 4286 4287 if (field->hasAttr<AnnotateAttr>()) 4288 addr = EmitFieldAnnotations(field, addr); 4289 4290 LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo); 4291 LV.getQuals().addCVRQualifiers(RecordCVR); 4292 4293 // __weak attribute on a field is ignored. 4294 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak) 4295 LV.getQuals().removeObjCGCAttr(); 4296 4297 return LV; 4298 } 4299 4300 LValue 4301 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base, 4302 const FieldDecl *Field) { 4303 QualType FieldType = Field->getType(); 4304 4305 if (!FieldType->isReferenceType()) 4306 return EmitLValueForField(Base, Field); 4307 4308 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(*this), Field); 4309 4310 // Make sure that the address is pointing to the right type. 4311 llvm::Type *llvmType = ConvertTypeForMem(FieldType); 4312 V = Builder.CreateElementBitCast(V, llvmType, Field->getName()); 4313 4314 // TODO: Generate TBAA information that describes this access as a structure 4315 // member access and not just an access to an object of the field's type. This 4316 // should be similar to what we do in EmitLValueForField(). 4317 LValueBaseInfo BaseInfo = Base.getBaseInfo(); 4318 AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource(); 4319 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource)); 4320 return MakeAddrLValue(V, FieldType, FieldBaseInfo, 4321 CGM.getTBAAInfoForSubobject(Base, FieldType)); 4322 } 4323 4324 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){ 4325 if (E->isFileScope()) { 4326 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E); 4327 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl); 4328 } 4329 if (E->getType()->isVariablyModifiedType()) 4330 // make sure to emit the VLA size. 4331 EmitVariablyModifiedType(E->getType()); 4332 4333 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral"); 4334 const Expr *InitExpr = E->getInitializer(); 4335 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl); 4336 4337 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(), 4338 /*Init*/ true); 4339 4340 // Block-scope compound literals are destroyed at the end of the enclosing 4341 // scope in C. 4342 if (!getLangOpts().CPlusPlus) 4343 if (QualType::DestructionKind DtorKind = E->getType().isDestructedType()) 4344 pushLifetimeExtendedDestroy(getCleanupKind(DtorKind), DeclPtr, 4345 E->getType(), getDestroyer(DtorKind), 4346 DtorKind & EHCleanup); 4347 4348 return Result; 4349 } 4350 4351 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) { 4352 if (!E->isGLValue()) 4353 // Initializing an aggregate temporary in C++11: T{...}. 4354 return EmitAggExprToLValue(E); 4355 4356 // An lvalue initializer list must be initializing a reference. 4357 assert(E->isTransparent() && "non-transparent glvalue init list"); 4358 return EmitLValue(E->getInit(0)); 4359 } 4360 4361 /// Emit the operand of a glvalue conditional operator. This is either a glvalue 4362 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no 4363 /// LValue is returned and the current block has been terminated. 4364 static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF, 4365 const Expr *Operand) { 4366 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) { 4367 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false); 4368 return None; 4369 } 4370 4371 return CGF.EmitLValue(Operand); 4372 } 4373 4374 LValue CodeGenFunction:: 4375 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) { 4376 if (!expr->isGLValue()) { 4377 // ?: here should be an aggregate. 4378 assert(hasAggregateEvaluationKind(expr->getType()) && 4379 "Unexpected conditional operator!"); 4380 return EmitAggExprToLValue(expr); 4381 } 4382 4383 OpaqueValueMapping binding(*this, expr); 4384 4385 const Expr *condExpr = expr->getCond(); 4386 bool CondExprBool; 4387 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) { 4388 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr(); 4389 if (!CondExprBool) std::swap(live, dead); 4390 4391 if (!ContainsLabel(dead)) { 4392 // If the true case is live, we need to track its region. 4393 if (CondExprBool) 4394 incrementProfileCounter(expr); 4395 // If a throw expression we emit it and return an undefined lvalue 4396 // because it can't be used. 4397 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(live->IgnoreParens())) { 4398 EmitCXXThrowExpr(ThrowExpr); 4399 llvm::Type *Ty = 4400 llvm::PointerType::getUnqual(ConvertType(dead->getType())); 4401 return MakeAddrLValue( 4402 Address(llvm::UndefValue::get(Ty), CharUnits::One()), 4403 dead->getType()); 4404 } 4405 return EmitLValue(live); 4406 } 4407 } 4408 4409 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true"); 4410 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false"); 4411 llvm::BasicBlock *contBlock = createBasicBlock("cond.end"); 4412 4413 ConditionalEvaluation eval(*this); 4414 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr)); 4415 4416 // Any temporaries created here are conditional. 4417 EmitBlock(lhsBlock); 4418 incrementProfileCounter(expr); 4419 eval.begin(*this); 4420 Optional<LValue> lhs = 4421 EmitLValueOrThrowExpression(*this, expr->getTrueExpr()); 4422 eval.end(*this); 4423 4424 if (lhs && !lhs->isSimple()) 4425 return EmitUnsupportedLValue(expr, "conditional operator"); 4426 4427 lhsBlock = Builder.GetInsertBlock(); 4428 if (lhs) 4429 Builder.CreateBr(contBlock); 4430 4431 // Any temporaries created here are conditional. 4432 EmitBlock(rhsBlock); 4433 eval.begin(*this); 4434 Optional<LValue> rhs = 4435 EmitLValueOrThrowExpression(*this, expr->getFalseExpr()); 4436 eval.end(*this); 4437 if (rhs && !rhs->isSimple()) 4438 return EmitUnsupportedLValue(expr, "conditional operator"); 4439 rhsBlock = Builder.GetInsertBlock(); 4440 4441 EmitBlock(contBlock); 4442 4443 if (lhs && rhs) { 4444 llvm::PHINode *phi = 4445 Builder.CreatePHI(lhs->getPointer(*this)->getType(), 2, "cond-lvalue"); 4446 phi->addIncoming(lhs->getPointer(*this), lhsBlock); 4447 phi->addIncoming(rhs->getPointer(*this), rhsBlock); 4448 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment())); 4449 AlignmentSource alignSource = 4450 std::max(lhs->getBaseInfo().getAlignmentSource(), 4451 rhs->getBaseInfo().getAlignmentSource()); 4452 TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator( 4453 lhs->getTBAAInfo(), rhs->getTBAAInfo()); 4454 return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource), 4455 TBAAInfo); 4456 } else { 4457 assert((lhs || rhs) && 4458 "both operands of glvalue conditional are throw-expressions?"); 4459 return lhs ? *lhs : *rhs; 4460 } 4461 } 4462 4463 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference 4464 /// type. If the cast is to a reference, we can have the usual lvalue result, 4465 /// otherwise if a cast is needed by the code generator in an lvalue context, 4466 /// then it must mean that we need the address of an aggregate in order to 4467 /// access one of its members. This can happen for all the reasons that casts 4468 /// are permitted with aggregate result, including noop aggregate casts, and 4469 /// cast from scalar to union. 4470 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) { 4471 switch (E->getCastKind()) { 4472 case CK_ToVoid: 4473 case CK_BitCast: 4474 case CK_LValueToRValueBitCast: 4475 case CK_ArrayToPointerDecay: 4476 case CK_FunctionToPointerDecay: 4477 case CK_NullToMemberPointer: 4478 case CK_NullToPointer: 4479 case CK_IntegralToPointer: 4480 case CK_PointerToIntegral: 4481 case CK_PointerToBoolean: 4482 case CK_VectorSplat: 4483 case CK_IntegralCast: 4484 case CK_BooleanToSignedIntegral: 4485 case CK_IntegralToBoolean: 4486 case CK_IntegralToFloating: 4487 case CK_FloatingToIntegral: 4488 case CK_FloatingToBoolean: 4489 case CK_FloatingCast: 4490 case CK_FloatingRealToComplex: 4491 case CK_FloatingComplexToReal: 4492 case CK_FloatingComplexToBoolean: 4493 case CK_FloatingComplexCast: 4494 case CK_FloatingComplexToIntegralComplex: 4495 case CK_IntegralRealToComplex: 4496 case CK_IntegralComplexToReal: 4497 case CK_IntegralComplexToBoolean: 4498 case CK_IntegralComplexCast: 4499 case CK_IntegralComplexToFloatingComplex: 4500 case CK_DerivedToBaseMemberPointer: 4501 case CK_BaseToDerivedMemberPointer: 4502 case CK_MemberPointerToBoolean: 4503 case CK_ReinterpretMemberPointer: 4504 case CK_AnyPointerToBlockPointerCast: 4505 case CK_ARCProduceObject: 4506 case CK_ARCConsumeObject: 4507 case CK_ARCReclaimReturnedObject: 4508 case CK_ARCExtendBlockObject: 4509 case CK_CopyAndAutoreleaseBlockObject: 4510 case CK_IntToOCLSampler: 4511 case CK_FixedPointCast: 4512 case CK_FixedPointToBoolean: 4513 case CK_FixedPointToIntegral: 4514 case CK_IntegralToFixedPoint: 4515 return EmitUnsupportedLValue(E, "unexpected cast lvalue"); 4516 4517 case CK_Dependent: 4518 llvm_unreachable("dependent cast kind in IR gen!"); 4519 4520 case CK_BuiltinFnToFnPtr: 4521 llvm_unreachable("builtin functions are handled elsewhere"); 4522 4523 // These are never l-values; just use the aggregate emission code. 4524 case CK_NonAtomicToAtomic: 4525 case CK_AtomicToNonAtomic: 4526 return EmitAggExprToLValue(E); 4527 4528 case CK_Dynamic: { 4529 LValue LV = EmitLValue(E->getSubExpr()); 4530 Address V = LV.getAddress(*this); 4531 const auto *DCE = cast<CXXDynamicCastExpr>(E); 4532 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType()); 4533 } 4534 4535 case CK_ConstructorConversion: 4536 case CK_UserDefinedConversion: 4537 case CK_CPointerToObjCPointerCast: 4538 case CK_BlockPointerToObjCPointerCast: 4539 case CK_NoOp: 4540 case CK_LValueToRValue: 4541 return EmitLValue(E->getSubExpr()); 4542 4543 case CK_UncheckedDerivedToBase: 4544 case CK_DerivedToBase: { 4545 const auto *DerivedClassTy = 4546 E->getSubExpr()->getType()->castAs<RecordType>(); 4547 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 4548 4549 LValue LV = EmitLValue(E->getSubExpr()); 4550 Address This = LV.getAddress(*this); 4551 4552 // Perform the derived-to-base conversion 4553 Address Base = GetAddressOfBaseClass( 4554 This, DerivedClassDecl, E->path_begin(), E->path_end(), 4555 /*NullCheckValue=*/false, E->getExprLoc()); 4556 4557 // TODO: Support accesses to members of base classes in TBAA. For now, we 4558 // conservatively pretend that the complete object is of the base class 4559 // type. 4560 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(), 4561 CGM.getTBAAInfoForSubobject(LV, E->getType())); 4562 } 4563 case CK_ToUnion: 4564 return EmitAggExprToLValue(E); 4565 case CK_BaseToDerived: { 4566 const auto *DerivedClassTy = E->getType()->castAs<RecordType>(); 4567 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 4568 4569 LValue LV = EmitLValue(E->getSubExpr()); 4570 4571 // Perform the base-to-derived conversion 4572 Address Derived = GetAddressOfDerivedClass( 4573 LV.getAddress(*this), DerivedClassDecl, E->path_begin(), E->path_end(), 4574 /*NullCheckValue=*/false); 4575 4576 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is 4577 // performed and the object is not of the derived type. 4578 if (sanitizePerformTypeCheck()) 4579 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(), 4580 Derived.getPointer(), E->getType()); 4581 4582 if (SanOpts.has(SanitizerKind::CFIDerivedCast)) 4583 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(), 4584 /*MayBeNull=*/false, CFITCK_DerivedCast, 4585 E->getBeginLoc()); 4586 4587 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(), 4588 CGM.getTBAAInfoForSubobject(LV, E->getType())); 4589 } 4590 case CK_LValueBitCast: { 4591 // This must be a reinterpret_cast (or c-style equivalent). 4592 const auto *CE = cast<ExplicitCastExpr>(E); 4593 4594 CGM.EmitExplicitCastExprType(CE, this); 4595 LValue LV = EmitLValue(E->getSubExpr()); 4596 Address V = Builder.CreateBitCast(LV.getAddress(*this), 4597 ConvertType(CE->getTypeAsWritten())); 4598 4599 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast)) 4600 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(), 4601 /*MayBeNull=*/false, CFITCK_UnrelatedCast, 4602 E->getBeginLoc()); 4603 4604 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(), 4605 CGM.getTBAAInfoForSubobject(LV, E->getType())); 4606 } 4607 case CK_AddressSpaceConversion: { 4608 LValue LV = EmitLValue(E->getSubExpr()); 4609 QualType DestTy = getContext().getPointerType(E->getType()); 4610 llvm::Value *V = getTargetHooks().performAddrSpaceCast( 4611 *this, LV.getPointer(*this), 4612 E->getSubExpr()->getType().getAddressSpace(), 4613 E->getType().getAddressSpace(), ConvertType(DestTy)); 4614 return MakeAddrLValue(Address(V, LV.getAddress(*this).getAlignment()), 4615 E->getType(), LV.getBaseInfo(), LV.getTBAAInfo()); 4616 } 4617 case CK_ObjCObjectLValueCast: { 4618 LValue LV = EmitLValue(E->getSubExpr()); 4619 Address V = Builder.CreateElementBitCast(LV.getAddress(*this), 4620 ConvertType(E->getType())); 4621 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(), 4622 CGM.getTBAAInfoForSubobject(LV, E->getType())); 4623 } 4624 case CK_ZeroToOCLOpaqueType: 4625 llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid"); 4626 } 4627 4628 llvm_unreachable("Unhandled lvalue cast kind?"); 4629 } 4630 4631 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) { 4632 assert(OpaqueValueMappingData::shouldBindAsLValue(e)); 4633 return getOrCreateOpaqueLValueMapping(e); 4634 } 4635 4636 LValue 4637 CodeGenFunction::getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e) { 4638 assert(OpaqueValueMapping::shouldBindAsLValue(e)); 4639 4640 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator 4641 it = OpaqueLValues.find(e); 4642 4643 if (it != OpaqueLValues.end()) 4644 return it->second; 4645 4646 assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted"); 4647 return EmitLValue(e->getSourceExpr()); 4648 } 4649 4650 RValue 4651 CodeGenFunction::getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e) { 4652 assert(!OpaqueValueMapping::shouldBindAsLValue(e)); 4653 4654 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator 4655 it = OpaqueRValues.find(e); 4656 4657 if (it != OpaqueRValues.end()) 4658 return it->second; 4659 4660 assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted"); 4661 return EmitAnyExpr(e->getSourceExpr()); 4662 } 4663 4664 RValue CodeGenFunction::EmitRValueForField(LValue LV, 4665 const FieldDecl *FD, 4666 SourceLocation Loc) { 4667 QualType FT = FD->getType(); 4668 LValue FieldLV = EmitLValueForField(LV, FD); 4669 switch (getEvaluationKind(FT)) { 4670 case TEK_Complex: 4671 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc)); 4672 case TEK_Aggregate: 4673 return FieldLV.asAggregateRValue(*this); 4674 case TEK_Scalar: 4675 // This routine is used to load fields one-by-one to perform a copy, so 4676 // don't load reference fields. 4677 if (FD->getType()->isReferenceType()) 4678 return RValue::get(FieldLV.getPointer(*this)); 4679 // Call EmitLoadOfScalar except when the lvalue is a bitfield to emit a 4680 // primitive load. 4681 if (FieldLV.isBitField()) 4682 return EmitLoadOfLValue(FieldLV, Loc); 4683 return RValue::get(EmitLoadOfScalar(FieldLV, Loc)); 4684 } 4685 llvm_unreachable("bad evaluation kind"); 4686 } 4687 4688 //===--------------------------------------------------------------------===// 4689 // Expression Emission 4690 //===--------------------------------------------------------------------===// 4691 4692 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E, 4693 ReturnValueSlot ReturnValue) { 4694 // Builtins never have block type. 4695 if (E->getCallee()->getType()->isBlockPointerType()) 4696 return EmitBlockCallExpr(E, ReturnValue); 4697 4698 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E)) 4699 return EmitCXXMemberCallExpr(CE, ReturnValue); 4700 4701 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E)) 4702 return EmitCUDAKernelCallExpr(CE, ReturnValue); 4703 4704 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E)) 4705 if (const CXXMethodDecl *MD = 4706 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl())) 4707 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue); 4708 4709 CGCallee callee = EmitCallee(E->getCallee()); 4710 4711 if (callee.isBuiltin()) { 4712 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(), 4713 E, ReturnValue); 4714 } 4715 4716 if (callee.isPseudoDestructor()) { 4717 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr()); 4718 } 4719 4720 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue); 4721 } 4722 4723 /// Emit a CallExpr without considering whether it might be a subclass. 4724 RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E, 4725 ReturnValueSlot ReturnValue) { 4726 CGCallee Callee = EmitCallee(E->getCallee()); 4727 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue); 4728 } 4729 4730 static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD) { 4731 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 4732 4733 if (auto builtinID = FD->getBuiltinID()) { 4734 // Replaceable builtin provide their own implementation of a builtin. Unless 4735 // we are in the builtin implementation itself, don't call the actual 4736 // builtin. If we are in the builtin implementation, avoid trivial infinite 4737 // recursion. 4738 if (!FD->isInlineBuiltinDeclaration() || 4739 CGF.CurFn->getName() == FD->getName()) 4740 return CGCallee::forBuiltin(builtinID, FD); 4741 } 4742 4743 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, GD); 4744 return CGCallee::forDirect(calleePtr, GD); 4745 } 4746 4747 CGCallee CodeGenFunction::EmitCallee(const Expr *E) { 4748 E = E->IgnoreParens(); 4749 4750 // Look through function-to-pointer decay. 4751 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) { 4752 if (ICE->getCastKind() == CK_FunctionToPointerDecay || 4753 ICE->getCastKind() == CK_BuiltinFnToFnPtr) { 4754 return EmitCallee(ICE->getSubExpr()); 4755 } 4756 4757 // Resolve direct calls. 4758 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) { 4759 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 4760 return EmitDirectCallee(*this, FD); 4761 } 4762 } else if (auto ME = dyn_cast<MemberExpr>(E)) { 4763 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) { 4764 EmitIgnoredExpr(ME->getBase()); 4765 return EmitDirectCallee(*this, FD); 4766 } 4767 4768 // Look through template substitutions. 4769 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) { 4770 return EmitCallee(NTTP->getReplacement()); 4771 4772 // Treat pseudo-destructor calls differently. 4773 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) { 4774 return CGCallee::forPseudoDestructor(PDE); 4775 } 4776 4777 // Otherwise, we have an indirect reference. 4778 llvm::Value *calleePtr; 4779 QualType functionType; 4780 if (auto ptrType = E->getType()->getAs<PointerType>()) { 4781 calleePtr = EmitScalarExpr(E); 4782 functionType = ptrType->getPointeeType(); 4783 } else { 4784 functionType = E->getType(); 4785 calleePtr = EmitLValue(E).getPointer(*this); 4786 } 4787 assert(functionType->isFunctionType()); 4788 4789 GlobalDecl GD; 4790 if (const auto *VD = 4791 dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee())) 4792 GD = GlobalDecl(VD); 4793 4794 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD); 4795 CGCallee callee(calleeInfo, calleePtr); 4796 return callee; 4797 } 4798 4799 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) { 4800 // Comma expressions just emit their LHS then their RHS as an l-value. 4801 if (E->getOpcode() == BO_Comma) { 4802 EmitIgnoredExpr(E->getLHS()); 4803 EnsureInsertPoint(); 4804 return EmitLValue(E->getRHS()); 4805 } 4806 4807 if (E->getOpcode() == BO_PtrMemD || 4808 E->getOpcode() == BO_PtrMemI) 4809 return EmitPointerToDataMemberBinaryExpr(E); 4810 4811 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value"); 4812 4813 // Note that in all of these cases, __block variables need the RHS 4814 // evaluated first just in case the variable gets moved by the RHS. 4815 4816 switch (getEvaluationKind(E->getType())) { 4817 case TEK_Scalar: { 4818 switch (E->getLHS()->getType().getObjCLifetime()) { 4819 case Qualifiers::OCL_Strong: 4820 return EmitARCStoreStrong(E, /*ignored*/ false).first; 4821 4822 case Qualifiers::OCL_Autoreleasing: 4823 return EmitARCStoreAutoreleasing(E).first; 4824 4825 // No reason to do any of these differently. 4826 case Qualifiers::OCL_None: 4827 case Qualifiers::OCL_ExplicitNone: 4828 case Qualifiers::OCL_Weak: 4829 break; 4830 } 4831 4832 RValue RV = EmitAnyExpr(E->getRHS()); 4833 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store); 4834 if (RV.isScalar()) 4835 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc()); 4836 EmitStoreThroughLValue(RV, LV); 4837 if (getLangOpts().OpenMP) 4838 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this, 4839 E->getLHS()); 4840 return LV; 4841 } 4842 4843 case TEK_Complex: 4844 return EmitComplexAssignmentLValue(E); 4845 4846 case TEK_Aggregate: 4847 return EmitAggExprToLValue(E); 4848 } 4849 llvm_unreachable("bad evaluation kind"); 4850 } 4851 4852 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) { 4853 RValue RV = EmitCallExpr(E); 4854 4855 if (!RV.isScalar()) 4856 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(), 4857 AlignmentSource::Decl); 4858 4859 assert(E->getCallReturnType(getContext())->isReferenceType() && 4860 "Can't have a scalar return unless the return type is a " 4861 "reference type!"); 4862 4863 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType()); 4864 } 4865 4866 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) { 4867 // FIXME: This shouldn't require another copy. 4868 return EmitAggExprToLValue(E); 4869 } 4870 4871 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) { 4872 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor() 4873 && "binding l-value to type which needs a temporary"); 4874 AggValueSlot Slot = CreateAggTemp(E->getType()); 4875 EmitCXXConstructExpr(E, Slot); 4876 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl); 4877 } 4878 4879 LValue 4880 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) { 4881 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType()); 4882 } 4883 4884 Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) { 4885 return Builder.CreateElementBitCast(CGM.GetAddrOfMSGuidDecl(E->getGuidDecl()), 4886 ConvertType(E->getType())); 4887 } 4888 4889 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) { 4890 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(), 4891 AlignmentSource::Decl); 4892 } 4893 4894 LValue 4895 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) { 4896 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue"); 4897 Slot.setExternallyDestructed(); 4898 EmitAggExpr(E->getSubExpr(), Slot); 4899 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress()); 4900 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl); 4901 } 4902 4903 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) { 4904 RValue RV = EmitObjCMessageExpr(E); 4905 4906 if (!RV.isScalar()) 4907 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(), 4908 AlignmentSource::Decl); 4909 4910 assert(E->getMethodDecl()->getReturnType()->isReferenceType() && 4911 "Can't have a scalar return unless the return type is a " 4912 "reference type!"); 4913 4914 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType()); 4915 } 4916 4917 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) { 4918 Address V = 4919 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector()); 4920 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl); 4921 } 4922 4923 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface, 4924 const ObjCIvarDecl *Ivar) { 4925 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar); 4926 } 4927 4928 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy, 4929 llvm::Value *BaseValue, 4930 const ObjCIvarDecl *Ivar, 4931 unsigned CVRQualifiers) { 4932 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue, 4933 Ivar, CVRQualifiers); 4934 } 4935 4936 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) { 4937 // FIXME: A lot of the code below could be shared with EmitMemberExpr. 4938 llvm::Value *BaseValue = nullptr; 4939 const Expr *BaseExpr = E->getBase(); 4940 Qualifiers BaseQuals; 4941 QualType ObjectTy; 4942 if (E->isArrow()) { 4943 BaseValue = EmitScalarExpr(BaseExpr); 4944 ObjectTy = BaseExpr->getType()->getPointeeType(); 4945 BaseQuals = ObjectTy.getQualifiers(); 4946 } else { 4947 LValue BaseLV = EmitLValue(BaseExpr); 4948 BaseValue = BaseLV.getPointer(*this); 4949 ObjectTy = BaseExpr->getType(); 4950 BaseQuals = ObjectTy.getQualifiers(); 4951 } 4952 4953 LValue LV = 4954 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(), 4955 BaseQuals.getCVRQualifiers()); 4956 setObjCGCLValueClass(getContext(), E, LV); 4957 return LV; 4958 } 4959 4960 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) { 4961 // Can only get l-value for message expression returning aggregate type 4962 RValue RV = EmitAnyExprToTemp(E); 4963 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(), 4964 AlignmentSource::Decl); 4965 } 4966 4967 RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee, 4968 const CallExpr *E, ReturnValueSlot ReturnValue, 4969 llvm::Value *Chain) { 4970 // Get the actual function type. The callee type will always be a pointer to 4971 // function type or a block pointer type. 4972 assert(CalleeType->isFunctionPointerType() && 4973 "Call must have function pointer type!"); 4974 4975 const Decl *TargetDecl = 4976 OrigCallee.getAbstractInfo().getCalleeDecl().getDecl(); 4977 4978 CalleeType = getContext().getCanonicalType(CalleeType); 4979 4980 auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType(); 4981 4982 CGCallee Callee = OrigCallee; 4983 4984 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) && 4985 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) { 4986 if (llvm::Constant *PrefixSig = 4987 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) { 4988 SanitizerScope SanScope(this); 4989 // Remove any (C++17) exception specifications, to allow calling e.g. a 4990 // noexcept function through a non-noexcept pointer. 4991 auto ProtoTy = 4992 getContext().getFunctionTypeWithExceptionSpec(PointeeType, EST_None); 4993 llvm::Constant *FTRTTIConst = 4994 CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true); 4995 llvm::Type *PrefixStructTyElems[] = {PrefixSig->getType(), Int32Ty}; 4996 llvm::StructType *PrefixStructTy = llvm::StructType::get( 4997 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true); 4998 4999 llvm::Value *CalleePtr = Callee.getFunctionPointer(); 5000 5001 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast( 5002 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy)); 5003 llvm::Value *CalleeSigPtr = 5004 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0); 5005 llvm::Value *CalleeSig = 5006 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign()); 5007 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig); 5008 5009 llvm::BasicBlock *Cont = createBasicBlock("cont"); 5010 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck"); 5011 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont); 5012 5013 EmitBlock(TypeCheck); 5014 llvm::Value *CalleeRTTIPtr = 5015 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1); 5016 llvm::Value *CalleeRTTIEncoded = 5017 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign()); 5018 llvm::Value *CalleeRTTI = 5019 DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded); 5020 llvm::Value *CalleeRTTIMatch = 5021 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst); 5022 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()), 5023 EmitCheckTypeDescriptor(CalleeType)}; 5024 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function), 5025 SanitizerHandler::FunctionTypeMismatch, StaticData, 5026 {CalleePtr, CalleeRTTI, FTRTTIConst}); 5027 5028 Builder.CreateBr(Cont); 5029 EmitBlock(Cont); 5030 } 5031 } 5032 5033 const auto *FnType = cast<FunctionType>(PointeeType); 5034 5035 // If we are checking indirect calls and this call is indirect, check that the 5036 // function pointer is a member of the bit set for the function type. 5037 if (SanOpts.has(SanitizerKind::CFIICall) && 5038 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) { 5039 SanitizerScope SanScope(this); 5040 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall); 5041 5042 llvm::Metadata *MD; 5043 if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers) 5044 MD = CGM.CreateMetadataIdentifierGeneralized(QualType(FnType, 0)); 5045 else 5046 MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0)); 5047 5048 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD); 5049 5050 llvm::Value *CalleePtr = Callee.getFunctionPointer(); 5051 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy); 5052 llvm::Value *TypeTest = Builder.CreateCall( 5053 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId}); 5054 5055 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD); 5056 llvm::Constant *StaticData[] = { 5057 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall), 5058 EmitCheckSourceLocation(E->getBeginLoc()), 5059 EmitCheckTypeDescriptor(QualType(FnType, 0)), 5060 }; 5061 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) { 5062 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId, 5063 CastedCallee, StaticData); 5064 } else { 5065 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall), 5066 SanitizerHandler::CFICheckFail, StaticData, 5067 {CastedCallee, llvm::UndefValue::get(IntPtrTy)}); 5068 } 5069 } 5070 5071 CallArgList Args; 5072 if (Chain) 5073 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)), 5074 CGM.getContext().VoidPtrTy); 5075 5076 // C++17 requires that we evaluate arguments to a call using assignment syntax 5077 // right-to-left, and that we evaluate arguments to certain other operators 5078 // left-to-right. Note that we allow this to override the order dictated by 5079 // the calling convention on the MS ABI, which means that parameter 5080 // destruction order is not necessarily reverse construction order. 5081 // FIXME: Revisit this based on C++ committee response to unimplementability. 5082 EvaluationOrder Order = EvaluationOrder::Default; 5083 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) { 5084 if (OCE->isAssignmentOp()) 5085 Order = EvaluationOrder::ForceRightToLeft; 5086 else { 5087 switch (OCE->getOperator()) { 5088 case OO_LessLess: 5089 case OO_GreaterGreater: 5090 case OO_AmpAmp: 5091 case OO_PipePipe: 5092 case OO_Comma: 5093 case OO_ArrowStar: 5094 Order = EvaluationOrder::ForceLeftToRight; 5095 break; 5096 default: 5097 break; 5098 } 5099 } 5100 } 5101 5102 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(), 5103 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order); 5104 5105 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall( 5106 Args, FnType, /*ChainCall=*/Chain); 5107 5108 // C99 6.5.2.2p6: 5109 // If the expression that denotes the called function has a type 5110 // that does not include a prototype, [the default argument 5111 // promotions are performed]. If the number of arguments does not 5112 // equal the number of parameters, the behavior is undefined. If 5113 // the function is defined with a type that includes a prototype, 5114 // and either the prototype ends with an ellipsis (, ...) or the 5115 // types of the arguments after promotion are not compatible with 5116 // the types of the parameters, the behavior is undefined. If the 5117 // function is defined with a type that does not include a 5118 // prototype, and the types of the arguments after promotion are 5119 // not compatible with those of the parameters after promotion, 5120 // the behavior is undefined [except in some trivial cases]. 5121 // That is, in the general case, we should assume that a call 5122 // through an unprototyped function type works like a *non-variadic* 5123 // call. The way we make this work is to cast to the exact type 5124 // of the promoted arguments. 5125 // 5126 // Chain calls use this same code path to add the invisible chain parameter 5127 // to the function type. 5128 if (isa<FunctionNoProtoType>(FnType) || Chain) { 5129 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo); 5130 int AS = Callee.getFunctionPointer()->getType()->getPointerAddressSpace(); 5131 CalleeTy = CalleeTy->getPointerTo(AS); 5132 5133 llvm::Value *CalleePtr = Callee.getFunctionPointer(); 5134 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast"); 5135 Callee.setFunctionPointer(CalleePtr); 5136 } 5137 5138 llvm::CallBase *CallOrInvoke = nullptr; 5139 RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &CallOrInvoke, 5140 E->getExprLoc()); 5141 5142 // Generate function declaration DISuprogram in order to be used 5143 // in debug info about call sites. 5144 if (CGDebugInfo *DI = getDebugInfo()) { 5145 if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 5146 DI->EmitFuncDeclForCallSite(CallOrInvoke, QualType(FnType, 0), 5147 CalleeDecl); 5148 } 5149 5150 return Call; 5151 } 5152 5153 LValue CodeGenFunction:: 5154 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) { 5155 Address BaseAddr = Address::invalid(); 5156 if (E->getOpcode() == BO_PtrMemI) { 5157 BaseAddr = EmitPointerWithAlignment(E->getLHS()); 5158 } else { 5159 BaseAddr = EmitLValue(E->getLHS()).getAddress(*this); 5160 } 5161 5162 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS()); 5163 const auto *MPT = E->getRHS()->getType()->castAs<MemberPointerType>(); 5164 5165 LValueBaseInfo BaseInfo; 5166 TBAAAccessInfo TBAAInfo; 5167 Address MemberAddr = 5168 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo, 5169 &TBAAInfo); 5170 5171 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo); 5172 } 5173 5174 /// Given the address of a temporary variable, produce an r-value of 5175 /// its type. 5176 RValue CodeGenFunction::convertTempToRValue(Address addr, 5177 QualType type, 5178 SourceLocation loc) { 5179 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl); 5180 switch (getEvaluationKind(type)) { 5181 case TEK_Complex: 5182 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc)); 5183 case TEK_Aggregate: 5184 return lvalue.asAggregateRValue(*this); 5185 case TEK_Scalar: 5186 return RValue::get(EmitLoadOfScalar(lvalue, loc)); 5187 } 5188 llvm_unreachable("bad evaluation kind"); 5189 } 5190 5191 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) { 5192 assert(Val->getType()->isFPOrFPVectorTy()); 5193 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val)) 5194 return; 5195 5196 llvm::MDBuilder MDHelper(getLLVMContext()); 5197 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy); 5198 5199 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node); 5200 } 5201 5202 namespace { 5203 struct LValueOrRValue { 5204 LValue LV; 5205 RValue RV; 5206 }; 5207 } 5208 5209 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF, 5210 const PseudoObjectExpr *E, 5211 bool forLValue, 5212 AggValueSlot slot) { 5213 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques; 5214 5215 // Find the result expression, if any. 5216 const Expr *resultExpr = E->getResultExpr(); 5217 LValueOrRValue result; 5218 5219 for (PseudoObjectExpr::const_semantics_iterator 5220 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) { 5221 const Expr *semantic = *i; 5222 5223 // If this semantic expression is an opaque value, bind it 5224 // to the result of its source expression. 5225 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) { 5226 // Skip unique OVEs. 5227 if (ov->isUnique()) { 5228 assert(ov != resultExpr && 5229 "A unique OVE cannot be used as the result expression"); 5230 continue; 5231 } 5232 5233 // If this is the result expression, we may need to evaluate 5234 // directly into the slot. 5235 typedef CodeGenFunction::OpaqueValueMappingData OVMA; 5236 OVMA opaqueData; 5237 if (ov == resultExpr && ov->isRValue() && !forLValue && 5238 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) { 5239 CGF.EmitAggExpr(ov->getSourceExpr(), slot); 5240 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(), 5241 AlignmentSource::Decl); 5242 opaqueData = OVMA::bind(CGF, ov, LV); 5243 result.RV = slot.asRValue(); 5244 5245 // Otherwise, emit as normal. 5246 } else { 5247 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr()); 5248 5249 // If this is the result, also evaluate the result now. 5250 if (ov == resultExpr) { 5251 if (forLValue) 5252 result.LV = CGF.EmitLValue(ov); 5253 else 5254 result.RV = CGF.EmitAnyExpr(ov, slot); 5255 } 5256 } 5257 5258 opaques.push_back(opaqueData); 5259 5260 // Otherwise, if the expression is the result, evaluate it 5261 // and remember the result. 5262 } else if (semantic == resultExpr) { 5263 if (forLValue) 5264 result.LV = CGF.EmitLValue(semantic); 5265 else 5266 result.RV = CGF.EmitAnyExpr(semantic, slot); 5267 5268 // Otherwise, evaluate the expression in an ignored context. 5269 } else { 5270 CGF.EmitIgnoredExpr(semantic); 5271 } 5272 } 5273 5274 // Unbind all the opaques now. 5275 for (unsigned i = 0, e = opaques.size(); i != e; ++i) 5276 opaques[i].unbind(CGF); 5277 5278 return result; 5279 } 5280 5281 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E, 5282 AggValueSlot slot) { 5283 return emitPseudoObjectExpr(*this, E, false, slot).RV; 5284 } 5285 5286 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) { 5287 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV; 5288 } 5289