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