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