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