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