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