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