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