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