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