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