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