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