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