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