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