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