1 //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Expr nodes as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
15 #include "CodeGenModule.h"
18 #include "CGDebugInfo.h"
19 #include "CGRecordLayout.h"
20 #include "CGObjCRuntime.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "llvm/Intrinsics.h"
24 #include "clang/Frontend/CodeGenOptions.h"
25 #include "llvm/Target/TargetData.h"
26 using namespace clang;
27 using namespace CodeGen;
29 //===--------------------------------------------------------------------===//
30 // Miscellaneous Helper Methods
31 //===--------------------------------------------------------------------===//
33 llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
34 unsigned addressSpace =
35 cast<llvm::PointerType>(value->getType())->getAddressSpace();
37 const llvm::PointerType *destType = Int8PtrTy;
39 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
41 if (value->getType() == destType) return value;
42 return Builder.CreateBitCast(value, destType);
45 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
47 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
48 const llvm::Twine &Name) {
49 if (!Builder.isNamePreserving())
50 return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt);
51 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
54 void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
56 llvm::StoreInst *Store = new llvm::StoreInst(Init, Var);
57 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
58 Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
61 llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
62 const llvm::Twine &Name) {
63 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
64 // FIXME: Should we prefer the preferred type alignment here?
65 CharUnits Align = getContext().getTypeAlignInChars(Ty);
66 Alloc->setAlignment(Align.getQuantity());
70 llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
71 const llvm::Twine &Name) {
72 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
73 // FIXME: Should we prefer the preferred type alignment here?
74 CharUnits Align = getContext().getTypeAlignInChars(Ty);
75 Alloc->setAlignment(Align.getQuantity());
79 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
80 /// expression and compare the result against zero, returning an Int1Ty value.
81 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
82 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
83 llvm::Value *MemPtr = EmitScalarExpr(E);
84 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
87 QualType BoolTy = getContext().BoolTy;
88 if (!E->getType()->isAnyComplexType())
89 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
91 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
94 /// EmitIgnoredExpr - Emit code to compute the specified expression,
95 /// ignoring the result.
96 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
98 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
100 // Just emit it as an l-value and drop the result.
104 /// EmitAnyExpr - Emit code to compute the specified expression which
105 /// can have any type. The result is returned as an RValue struct.
106 /// If this is an aggregate expression, AggSlot indicates where the
107 /// result should be returned.
108 RValue CodeGenFunction::EmitAnyExpr(const Expr *E, AggValueSlot AggSlot,
110 if (!hasAggregateLLVMType(E->getType()))
111 return RValue::get(EmitScalarExpr(E, IgnoreResult));
112 else if (E->getType()->isAnyComplexType())
113 return RValue::getComplex(EmitComplexExpr(E, IgnoreResult, IgnoreResult));
115 EmitAggExpr(E, AggSlot, IgnoreResult);
116 return AggSlot.asRValue();
119 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
120 /// always be accessible even if no aggregate location is provided.
121 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
122 AggValueSlot AggSlot = AggValueSlot::ignored();
124 if (hasAggregateLLVMType(E->getType()) &&
125 !E->getType()->isAnyComplexType())
126 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
127 return EmitAnyExpr(E, AggSlot);
130 /// EmitAnyExprToMem - Evaluate an expression into a given memory
132 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
133 llvm::Value *Location,
134 bool IsLocationVolatile,
136 if (E->getType()->isComplexType())
137 EmitComplexExprIntoAddr(E, Location, IsLocationVolatile);
138 else if (hasAggregateLLVMType(E->getType()))
139 EmitAggExpr(E, AggValueSlot::forAddr(Location, IsLocationVolatile, IsInit));
141 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
142 LValue LV = MakeAddrLValue(Location, E->getType());
143 EmitStoreThroughLValue(RV, LV, E->getType());
148 /// \brief An adjustment to be made to the temporary created when emitting a
149 /// reference binding, which accesses a particular subobject of that temporary.
150 struct SubobjectAdjustment {
151 enum { DerivedToBaseAdjustment, FieldAdjustment } Kind;
155 const CastExpr *BasePath;
156 const CXXRecordDecl *DerivedClass;
162 SubobjectAdjustment(const CastExpr *BasePath,
163 const CXXRecordDecl *DerivedClass)
164 : Kind(DerivedToBaseAdjustment) {
165 DerivedToBase.BasePath = BasePath;
166 DerivedToBase.DerivedClass = DerivedClass;
169 SubobjectAdjustment(FieldDecl *Field)
170 : Kind(FieldAdjustment) {
177 CreateReferenceTemporary(CodeGenFunction& CGF, QualType Type,
178 const NamedDecl *InitializedDecl) {
179 if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
180 if (VD->hasGlobalStorage()) {
181 llvm::SmallString<256> Name;
182 llvm::raw_svector_ostream Out(Name);
183 CGF.CGM.getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
186 const llvm::Type *RefTempTy = CGF.ConvertTypeForMem(Type);
188 // Create the reference temporary.
189 llvm::GlobalValue *RefTemp =
190 new llvm::GlobalVariable(CGF.CGM.getModule(),
191 RefTempTy, /*isConstant=*/false,
192 llvm::GlobalValue::InternalLinkage,
193 llvm::Constant::getNullValue(RefTempTy),
199 return CGF.CreateMemTemp(Type, "ref.tmp");
203 EmitExprForReferenceBinding(CodeGenFunction &CGF, const Expr *E,
204 llvm::Value *&ReferenceTemporary,
205 const CXXDestructorDecl *&ReferenceTemporaryDtor,
206 const NamedDecl *InitializedDecl) {
207 if (const CXXDefaultArgExpr *DAE = dyn_cast<CXXDefaultArgExpr>(E))
210 if (const ExprWithCleanups *TE = dyn_cast<ExprWithCleanups>(E)) {
211 CodeGenFunction::RunCleanupsScope Scope(CGF);
213 return EmitExprForReferenceBinding(CGF, TE->getSubExpr(),
215 ReferenceTemporaryDtor,
219 if (const ObjCPropertyRefExpr *PRE =
220 dyn_cast<ObjCPropertyRefExpr>(E->IgnoreParenImpCasts()))
221 if (PRE->getGetterResultType()->isReferenceType())
225 if (E->isGLValue()) {
226 // Emit the expression as an lvalue.
227 LValue LV = CGF.EmitLValue(E);
228 if (LV.isPropertyRef()) {
229 RV = CGF.EmitLoadOfPropertyRefLValue(LV);
230 return RV.getScalarVal();
233 return LV.getAddress();
235 // We have to load the lvalue.
236 RV = CGF.EmitLoadOfLValue(LV, E->getType());
238 llvm::SmallVector<SubobjectAdjustment, 2> Adjustments;
240 E = E->IgnoreParens();
242 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
243 if ((CE->getCastKind() == CK_DerivedToBase ||
244 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
245 E->getType()->isRecordType()) {
246 E = CE->getSubExpr();
247 CXXRecordDecl *Derived
248 = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
249 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
253 if (CE->getCastKind() == CK_NoOp) {
254 E = CE->getSubExpr();
257 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
258 if (!ME->isArrow() && ME->getBase()->isRValue()) {
259 assert(ME->getBase()->getType()->isRecordType());
260 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
262 Adjustments.push_back(SubobjectAdjustment(Field));
268 if (const OpaqueValueExpr *opaque = dyn_cast<OpaqueValueExpr>(E))
269 if (opaque->getType()->isRecordType())
270 return CGF.EmitOpaqueValueLValue(opaque).getAddress();
276 // Create a reference temporary if necessary.
277 AggValueSlot AggSlot = AggValueSlot::ignored();
278 if (CGF.hasAggregateLLVMType(E->getType()) &&
279 !E->getType()->isAnyComplexType()) {
280 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
282 AggSlot = AggValueSlot::forAddr(ReferenceTemporary, false,
283 InitializedDecl != 0);
286 RV = CGF.EmitAnyExpr(E, AggSlot);
288 if (InitializedDecl) {
289 // Get the destructor for the reference temporary.
290 if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
291 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
292 if (!ClassDecl->hasTrivialDestructor())
293 ReferenceTemporaryDtor = ClassDecl->getDestructor();
297 // Check if need to perform derived-to-base casts and/or field accesses, to
298 // get from the temporary object we created (and, potentially, for which we
299 // extended the lifetime) to the subobject we're binding the reference to.
300 if (!Adjustments.empty()) {
301 llvm::Value *Object = RV.getAggregateAddr();
302 for (unsigned I = Adjustments.size(); I != 0; --I) {
303 SubobjectAdjustment &Adjustment = Adjustments[I-1];
304 switch (Adjustment.Kind) {
305 case SubobjectAdjustment::DerivedToBaseAdjustment:
307 CGF.GetAddressOfBaseClass(Object,
308 Adjustment.DerivedToBase.DerivedClass,
309 Adjustment.DerivedToBase.BasePath->path_begin(),
310 Adjustment.DerivedToBase.BasePath->path_end(),
311 /*NullCheckValue=*/false);
314 case SubobjectAdjustment::FieldAdjustment: {
316 CGF.EmitLValueForField(Object, Adjustment.Field, 0);
318 Object = LV.getAddress();
322 // For non-simple lvalues, we actually have to create a copy of
323 // the object we're binding to.
324 QualType T = Adjustment.Field->getType().getNonReferenceType()
325 .getUnqualifiedType();
326 Object = CreateReferenceTemporary(CGF, T, InitializedDecl);
327 LValue TempLV = CGF.MakeAddrLValue(Object,
328 Adjustment.Field->getType());
329 CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV, T), TempLV, T);
340 if (RV.isAggregate())
341 return RV.getAggregateAddr();
343 // Create a temporary variable that we can bind the reference to.
344 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
349 CGF.getContext().getTypeAlignInChars(E->getType()).getQuantity();
351 CGF.EmitStoreOfScalar(RV.getScalarVal(), ReferenceTemporary,
352 /*Volatile=*/false, Alignment, E->getType());
354 CGF.StoreComplexToAddr(RV.getComplexVal(), ReferenceTemporary,
356 return ReferenceTemporary;
360 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E,
361 const NamedDecl *InitializedDecl) {
362 llvm::Value *ReferenceTemporary = 0;
363 const CXXDestructorDecl *ReferenceTemporaryDtor = 0;
364 llvm::Value *Value = EmitExprForReferenceBinding(*this, E, ReferenceTemporary,
365 ReferenceTemporaryDtor,
367 if (!ReferenceTemporaryDtor)
368 return RValue::get(Value);
370 // Make sure to call the destructor for the reference temporary.
371 if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
372 if (VD->hasGlobalStorage()) {
373 llvm::Constant *DtorFn =
374 CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete);
375 EmitCXXGlobalDtorRegistration(DtorFn,
376 cast<llvm::Constant>(ReferenceTemporary));
378 return RValue::get(Value);
382 PushDestructorCleanup(ReferenceTemporaryDtor, ReferenceTemporary);
384 return RValue::get(Value);
388 /// getAccessedFieldNo - Given an encoded value and a result number, return the
389 /// input field number being accessed.
390 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
391 const llvm::Constant *Elts) {
392 if (isa<llvm::ConstantAggregateZero>(Elts))
395 return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue();
398 void CodeGenFunction::EmitCheck(llvm::Value *Address, unsigned Size) {
402 // This needs to be to the standard address space.
403 Address = Builder.CreateBitCast(Address, Int8PtrTy);
405 const llvm::Type *IntPtrT = IntPtrTy;
406 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, &IntPtrT, 1);
408 // In time, people may want to control this and use a 1 here.
409 llvm::Value *Arg = Builder.getFalse();
410 llvm::Value *C = Builder.CreateCall2(F, Address, Arg);
411 llvm::BasicBlock *Cont = createBasicBlock();
412 llvm::BasicBlock *Check = createBasicBlock();
413 llvm::Value *NegativeOne = llvm::ConstantInt::get(IntPtrTy, -1ULL);
414 Builder.CreateCondBr(Builder.CreateICmpEQ(C, NegativeOne), Cont, Check);
417 Builder.CreateCondBr(Builder.CreateICmpUGE(C,
418 llvm::ConstantInt::get(IntPtrTy, Size)),
424 CodeGenFunction::ComplexPairTy CodeGenFunction::
425 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
426 bool isInc, bool isPre) {
427 ComplexPairTy InVal = LoadComplexFromAddr(LV.getAddress(),
428 LV.isVolatileQualified());
430 llvm::Value *NextVal;
431 if (isa<llvm::IntegerType>(InVal.first->getType())) {
432 uint64_t AmountVal = isInc ? 1 : -1;
433 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
435 // Add the inc/dec to the real part.
436 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
438 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
439 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
442 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
444 // Add the inc/dec to the real part.
445 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
448 ComplexPairTy IncVal(NextVal, InVal.second);
450 // Store the updated result through the lvalue.
451 StoreComplexToAddr(IncVal, LV.getAddress(), LV.isVolatileQualified());
453 // If this is a postinc, return the value read from memory, otherwise use the
455 return isPre ? IncVal : InVal;
459 //===----------------------------------------------------------------------===//
460 // LValue Expression Emission
461 //===----------------------------------------------------------------------===//
463 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
464 if (Ty->isVoidType())
465 return RValue::get(0);
467 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
468 const llvm::Type *EltTy = ConvertType(CTy->getElementType());
469 llvm::Value *U = llvm::UndefValue::get(EltTy);
470 return RValue::getComplex(std::make_pair(U, U));
473 // If this is a use of an undefined aggregate type, the aggregate must have an
474 // identifiable address. Just because the contents of the value are undefined
475 // doesn't mean that the address can't be taken and compared.
476 if (hasAggregateLLVMType(Ty)) {
477 llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
478 return RValue::getAggregate(DestPtr);
481 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
484 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
486 ErrorUnsupported(E, Name);
487 return GetUndefRValue(E->getType());
490 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
492 ErrorUnsupported(E, Name);
493 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
494 return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType());
497 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E) {
498 LValue LV = EmitLValue(E);
499 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
500 EmitCheck(LV.getAddress(),
501 getContext().getTypeSizeInChars(E->getType()).getQuantity());
505 /// EmitLValue - Emit code to compute a designator that specifies the location
506 /// of the expression.
508 /// This can return one of two things: a simple address or a bitfield reference.
509 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
510 /// an LLVM pointer type.
512 /// If this returns a bitfield reference, nothing about the pointee type of the
513 /// LLVM value is known: For example, it may not be a pointer to an integer.
515 /// If this returns a normal address, and if the lvalue's C type is fixed size,
516 /// this method guarantees that the returned pointer type will point to an LLVM
517 /// type of the same size of the lvalue's type. If the lvalue has a variable
518 /// length type, this is not possible.
520 LValue CodeGenFunction::EmitLValue(const Expr *E) {
521 switch (E->getStmtClass()) {
522 default: return EmitUnsupportedLValue(E, "l-value expression");
524 case Expr::ObjCSelectorExprClass:
525 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
526 case Expr::ObjCIsaExprClass:
527 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
528 case Expr::BinaryOperatorClass:
529 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
530 case Expr::CompoundAssignOperatorClass:
531 if (!E->getType()->isAnyComplexType())
532 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
533 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
534 case Expr::CallExprClass:
535 case Expr::CXXMemberCallExprClass:
536 case Expr::CXXOperatorCallExprClass:
537 return EmitCallExprLValue(cast<CallExpr>(E));
538 case Expr::VAArgExprClass:
539 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
540 case Expr::DeclRefExprClass:
541 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
542 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
543 case Expr::GenericSelectionExprClass:
544 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
545 case Expr::PredefinedExprClass:
546 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
547 case Expr::StringLiteralClass:
548 return EmitStringLiteralLValue(cast<StringLiteral>(E));
549 case Expr::ObjCEncodeExprClass:
550 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
552 case Expr::BlockDeclRefExprClass:
553 return EmitBlockDeclRefLValue(cast<BlockDeclRefExpr>(E));
555 case Expr::CXXTemporaryObjectExprClass:
556 case Expr::CXXConstructExprClass:
557 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
558 case Expr::CXXBindTemporaryExprClass:
559 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
560 case Expr::ExprWithCleanupsClass:
561 return EmitExprWithCleanupsLValue(cast<ExprWithCleanups>(E));
562 case Expr::CXXScalarValueInitExprClass:
563 return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E));
564 case Expr::CXXDefaultArgExprClass:
565 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
566 case Expr::CXXTypeidExprClass:
567 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
569 case Expr::ObjCMessageExprClass:
570 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
571 case Expr::ObjCIvarRefExprClass:
572 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
573 case Expr::ObjCPropertyRefExprClass:
574 return EmitObjCPropertyRefLValue(cast<ObjCPropertyRefExpr>(E));
575 case Expr::StmtExprClass:
576 return EmitStmtExprLValue(cast<StmtExpr>(E));
577 case Expr::UnaryOperatorClass:
578 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
579 case Expr::ArraySubscriptExprClass:
580 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
581 case Expr::ExtVectorElementExprClass:
582 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
583 case Expr::MemberExprClass:
584 return EmitMemberExpr(cast<MemberExpr>(E));
585 case Expr::CompoundLiteralExprClass:
586 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
587 case Expr::ConditionalOperatorClass:
588 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
589 case Expr::BinaryConditionalOperatorClass:
590 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
591 case Expr::ChooseExprClass:
592 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext()));
593 case Expr::OpaqueValueExprClass:
594 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
595 case Expr::ImplicitCastExprClass:
596 case Expr::CStyleCastExprClass:
597 case Expr::CXXFunctionalCastExprClass:
598 case Expr::CXXStaticCastExprClass:
599 case Expr::CXXDynamicCastExprClass:
600 case Expr::CXXReinterpretCastExprClass:
601 case Expr::CXXConstCastExprClass:
602 return EmitCastLValue(cast<CastExpr>(E));
606 llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
607 unsigned Alignment, QualType Ty,
608 llvm::MDNode *TBAAInfo) {
609 llvm::LoadInst *Load = Builder.CreateLoad(Addr, "tmp");
611 Load->setVolatile(true);
613 Load->setAlignment(Alignment);
615 CGM.DecorateInstruction(Load, TBAAInfo);
617 return EmitFromMemory(Load, Ty);
620 static bool isBooleanUnderlyingType(QualType Ty) {
621 if (const EnumType *ET = dyn_cast<EnumType>(Ty))
622 return ET->getDecl()->getIntegerType()->isBooleanType();
626 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
627 // Bool has a different representation in memory than in registers.
628 if (Ty->isBooleanType() || isBooleanUnderlyingType(Ty)) {
629 // This should really always be an i1, but sometimes it's already
630 // an i8, and it's awkward to track those cases down.
631 if (Value->getType()->isIntegerTy(1))
632 return Builder.CreateZExt(Value, Builder.getInt8Ty(), "frombool");
633 assert(Value->getType()->isIntegerTy(8) && "value rep of bool not i1/i8");
639 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
640 // Bool has a different representation in memory than in registers.
641 if (Ty->isBooleanType() || isBooleanUnderlyingType(Ty)) {
642 assert(Value->getType()->isIntegerTy(8) && "memory rep of bool not i8");
643 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
649 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
650 bool Volatile, unsigned Alignment,
652 llvm::MDNode *TBAAInfo) {
653 Value = EmitToMemory(Value, Ty);
654 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
656 Store->setAlignment(Alignment);
658 CGM.DecorateInstruction(Store, TBAAInfo);
661 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
662 /// method emits the address of the lvalue, then loads the result as an rvalue,
663 /// returning the rvalue.
664 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
665 if (LV.isObjCWeak()) {
666 // load of a __weak object.
667 llvm::Value *AddrWeakObj = LV.getAddress();
668 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
673 llvm::Value *Ptr = LV.getAddress();
675 // Functions are l-values that don't require loading.
676 if (ExprType->isFunctionType())
677 return RValue::get(Ptr);
679 // Everything needs a load.
680 return RValue::get(EmitLoadOfScalar(Ptr, LV.isVolatileQualified(),
681 LV.getAlignment(), ExprType,
686 if (LV.isVectorElt()) {
687 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(),
688 LV.isVolatileQualified(), "tmp");
689 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
693 // If this is a reference to a subset of the elements of a vector, either
694 // shuffle the input or extract/insert them as appropriate.
695 if (LV.isExtVectorElt())
696 return EmitLoadOfExtVectorElementLValue(LV, ExprType);
699 return EmitLoadOfBitfieldLValue(LV, ExprType);
701 assert(LV.isPropertyRef() && "Unknown LValue type!");
702 return EmitLoadOfPropertyRefLValue(LV);
705 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
707 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
709 // Get the output type.
710 const llvm::Type *ResLTy = ConvertType(ExprType);
711 unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy);
713 // Compute the result as an OR of all of the individual component accesses.
714 llvm::Value *Res = 0;
715 for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
716 const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
718 // Get the field pointer.
719 llvm::Value *Ptr = LV.getBitFieldBaseAddr();
721 // Only offset by the field index if used, so that incoming values are not
722 // required to be structures.
724 Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
726 // Offset by the byte offset, if used.
727 if (!AI.FieldByteOffset.isZero()) {
728 Ptr = EmitCastToVoidPtr(Ptr);
729 Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset.getQuantity(),
733 // Cast to the access type.
734 const llvm::Type *PTy = llvm::Type::getIntNPtrTy(getLLVMContext(),
736 CGM.getContext().getTargetAddressSpace(ExprType));
737 Ptr = Builder.CreateBitCast(Ptr, PTy);
740 llvm::LoadInst *Load = Builder.CreateLoad(Ptr, LV.isVolatileQualified());
741 if (!AI.AccessAlignment.isZero())
742 Load->setAlignment(AI.AccessAlignment.getQuantity());
744 // Shift out unused low bits and mask out unused high bits.
745 llvm::Value *Val = Load;
746 if (AI.FieldBitStart)
747 Val = Builder.CreateLShr(Load, AI.FieldBitStart);
748 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(AI.AccessWidth,
752 // Extend or truncate to the target size.
753 if (AI.AccessWidth < ResSizeInBits)
754 Val = Builder.CreateZExt(Val, ResLTy);
755 else if (AI.AccessWidth > ResSizeInBits)
756 Val = Builder.CreateTrunc(Val, ResLTy);
758 // Shift into place, and OR into the result.
759 if (AI.TargetBitOffset)
760 Val = Builder.CreateShl(Val, AI.TargetBitOffset);
761 Res = Res ? Builder.CreateOr(Res, Val) : Val;
764 // If the bit-field is signed, perform the sign-extension.
766 // FIXME: This can easily be folded into the load of the high bits, which
767 // could also eliminate the mask of high bits in some situations.
768 if (Info.isSigned()) {
769 unsigned ExtraBits = ResSizeInBits - Info.getSize();
771 Res = Builder.CreateAShr(Builder.CreateShl(Res, ExtraBits),
772 ExtraBits, "bf.val.sext");
775 return RValue::get(Res);
778 // If this is a reference to a subset of the elements of a vector, create an
779 // appropriate shufflevector.
780 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV,
782 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(),
783 LV.isVolatileQualified(), "tmp");
785 const llvm::Constant *Elts = LV.getExtVectorElts();
787 // If the result of the expression is a non-vector type, we must be extracting
788 // a single element. Just codegen as an extractelement.
789 const VectorType *ExprVT = ExprType->getAs<VectorType>();
791 unsigned InIdx = getAccessedFieldNo(0, Elts);
792 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
793 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
796 // Always use shuffle vector to try to retain the original program structure
797 unsigned NumResultElts = ExprVT->getNumElements();
799 llvm::SmallVector<llvm::Constant*, 4> Mask;
800 for (unsigned i = 0; i != NumResultElts; ++i) {
801 unsigned InIdx = getAccessedFieldNo(i, Elts);
802 Mask.push_back(llvm::ConstantInt::get(Int32Ty, InIdx));
805 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
806 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
808 return RValue::get(Vec);
813 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
814 /// lvalue, where both are guaranteed to the have the same type, and that type
816 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
818 if (!Dst.isSimple()) {
819 if (Dst.isVectorElt()) {
820 // Read/modify/write the vector, inserting the new element.
821 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(),
822 Dst.isVolatileQualified(), "tmp");
823 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
824 Dst.getVectorIdx(), "vecins");
825 Builder.CreateStore(Vec, Dst.getVectorAddr(),Dst.isVolatileQualified());
829 // If this is an update of extended vector elements, insert them as
831 if (Dst.isExtVectorElt())
832 return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty);
834 if (Dst.isBitField())
835 return EmitStoreThroughBitfieldLValue(Src, Dst, Ty);
837 assert(Dst.isPropertyRef() && "Unknown LValue type");
838 return EmitStoreThroughPropertyRefLValue(Src, Dst);
841 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
842 // load of a __weak object.
843 llvm::Value *LvalueDst = Dst.getAddress();
844 llvm::Value *src = Src.getScalarVal();
845 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
849 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
850 // load of a __strong object.
851 llvm::Value *LvalueDst = Dst.getAddress();
852 llvm::Value *src = Src.getScalarVal();
853 if (Dst.isObjCIvar()) {
854 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
855 const llvm::Type *ResultType = ConvertType(getContext().LongTy);
856 llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
857 llvm::Value *dst = RHS;
858 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
860 Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
861 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
862 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
864 } else if (Dst.isGlobalObjCRef()) {
865 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
866 Dst.isThreadLocalRef());
869 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
873 assert(Src.isScalar() && "Can't emit an agg store with this method");
874 EmitStoreOfScalar(Src.getScalarVal(), Dst.getAddress(),
875 Dst.isVolatileQualified(), Dst.getAlignment(), Ty,
879 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
881 llvm::Value **Result) {
882 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
884 // Get the output type.
885 const llvm::Type *ResLTy = ConvertTypeForMem(Ty);
886 unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy);
888 // Get the source value, truncated to the width of the bit-field.
889 llvm::Value *SrcVal = Src.getScalarVal();
891 if (Ty->isBooleanType())
892 SrcVal = Builder.CreateIntCast(SrcVal, ResLTy, /*IsSigned=*/false);
894 SrcVal = Builder.CreateAnd(SrcVal, llvm::APInt::getLowBitsSet(ResSizeInBits,
898 // Return the new value of the bit-field, if requested.
900 // Cast back to the proper type for result.
901 const llvm::Type *SrcTy = Src.getScalarVal()->getType();
902 llvm::Value *ReloadVal = Builder.CreateIntCast(SrcVal, SrcTy, false,
905 // Sign extend if necessary.
906 if (Info.isSigned()) {
907 unsigned ExtraBits = ResSizeInBits - Info.getSize();
909 ReloadVal = Builder.CreateAShr(Builder.CreateShl(ReloadVal, ExtraBits),
910 ExtraBits, "bf.reload.sext");
916 // Iterate over the components, writing each piece to memory.
917 for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
918 const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
920 // Get the field pointer.
921 llvm::Value *Ptr = Dst.getBitFieldBaseAddr();
922 unsigned addressSpace =
923 cast<llvm::PointerType>(Ptr->getType())->getAddressSpace();
925 // Only offset by the field index if used, so that incoming values are not
926 // required to be structures.
928 Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
930 // Offset by the byte offset, if used.
931 if (!AI.FieldByteOffset.isZero()) {
932 Ptr = EmitCastToVoidPtr(Ptr);
933 Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset.getQuantity(),
937 // Cast to the access type.
938 const llvm::Type *AccessLTy =
939 llvm::Type::getIntNTy(getLLVMContext(), AI.AccessWidth);
941 const llvm::Type *PTy = AccessLTy->getPointerTo(addressSpace);
942 Ptr = Builder.CreateBitCast(Ptr, PTy);
944 // Extract the piece of the bit-field value to write in this access, limited
945 // to the values that are part of this access.
946 llvm::Value *Val = SrcVal;
947 if (AI.TargetBitOffset)
948 Val = Builder.CreateLShr(Val, AI.TargetBitOffset);
949 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(ResSizeInBits,
952 // Extend or truncate to the access size.
953 if (ResSizeInBits < AI.AccessWidth)
954 Val = Builder.CreateZExt(Val, AccessLTy);
955 else if (ResSizeInBits > AI.AccessWidth)
956 Val = Builder.CreateTrunc(Val, AccessLTy);
958 // Shift into the position in memory.
959 if (AI.FieldBitStart)
960 Val = Builder.CreateShl(Val, AI.FieldBitStart);
962 // If necessary, load and OR in bits that are outside of the bit-field.
963 if (AI.TargetBitWidth != AI.AccessWidth) {
964 llvm::LoadInst *Load = Builder.CreateLoad(Ptr, Dst.isVolatileQualified());
965 if (!AI.AccessAlignment.isZero())
966 Load->setAlignment(AI.AccessAlignment.getQuantity());
968 // Compute the mask for zeroing the bits that are part of the bit-field.
969 llvm::APInt InvMask =
970 ~llvm::APInt::getBitsSet(AI.AccessWidth, AI.FieldBitStart,
971 AI.FieldBitStart + AI.TargetBitWidth);
973 // Apply the mask and OR in to the value to write.
974 Val = Builder.CreateOr(Builder.CreateAnd(Load, InvMask), Val);
978 llvm::StoreInst *Store = Builder.CreateStore(Val, Ptr,
979 Dst.isVolatileQualified());
980 if (!AI.AccessAlignment.isZero())
981 Store->setAlignment(AI.AccessAlignment.getQuantity());
985 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
988 // This access turns into a read/modify/write of the vector. Load the input
990 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(),
991 Dst.isVolatileQualified(), "tmp");
992 const llvm::Constant *Elts = Dst.getExtVectorElts();
994 llvm::Value *SrcVal = Src.getScalarVal();
996 if (const VectorType *VTy = Ty->getAs<VectorType>()) {
997 unsigned NumSrcElts = VTy->getNumElements();
998 unsigned NumDstElts =
999 cast<llvm::VectorType>(Vec->getType())->getNumElements();
1000 if (NumDstElts == NumSrcElts) {
1001 // Use shuffle vector is the src and destination are the same number of
1002 // elements and restore the vector mask since it is on the side it will be
1004 llvm::SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
1005 for (unsigned i = 0; i != NumSrcElts; ++i) {
1006 unsigned InIdx = getAccessedFieldNo(i, Elts);
1007 Mask[InIdx] = llvm::ConstantInt::get(Int32Ty, i);
1010 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1011 Vec = Builder.CreateShuffleVector(SrcVal,
1012 llvm::UndefValue::get(Vec->getType()),
1014 } else if (NumDstElts > NumSrcElts) {
1015 // Extended the source vector to the same length and then shuffle it
1016 // into the destination.
1017 // FIXME: since we're shuffling with undef, can we just use the indices
1018 // into that? This could be simpler.
1019 llvm::SmallVector<llvm::Constant*, 4> ExtMask;
1021 for (i = 0; i != NumSrcElts; ++i)
1022 ExtMask.push_back(llvm::ConstantInt::get(Int32Ty, i));
1023 for (; i != NumDstElts; ++i)
1024 ExtMask.push_back(llvm::UndefValue::get(Int32Ty));
1025 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
1026 llvm::Value *ExtSrcVal =
1027 Builder.CreateShuffleVector(SrcVal,
1028 llvm::UndefValue::get(SrcVal->getType()),
1031 llvm::SmallVector<llvm::Constant*, 4> Mask;
1032 for (unsigned i = 0; i != NumDstElts; ++i)
1033 Mask.push_back(llvm::ConstantInt::get(Int32Ty, i));
1035 // modify when what gets shuffled in
1036 for (unsigned i = 0; i != NumSrcElts; ++i) {
1037 unsigned Idx = getAccessedFieldNo(i, Elts);
1038 Mask[Idx] = llvm::ConstantInt::get(Int32Ty, i+NumDstElts);
1040 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1041 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV, "tmp");
1043 // We should never shorten the vector
1044 assert(0 && "unexpected shorten vector length");
1047 // If the Src is a scalar (not a vector) it must be updating one element.
1048 unsigned InIdx = getAccessedFieldNo(0, Elts);
1049 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
1050 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
1053 Builder.CreateStore(Vec, Dst.getExtVectorAddr(), Dst.isVolatileQualified());
1056 // setObjCGCLValueClass - sets class of he lvalue for the purpose of
1057 // generating write-barries API. It is currently a global, ivar,
1059 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
1061 if (Ctx.getLangOptions().getGCMode() == LangOptions::NonGC)
1064 if (isa<ObjCIvarRefExpr>(E)) {
1065 LV.setObjCIvar(true);
1066 ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E));
1067 LV.setBaseIvarExp(Exp->getBase());
1068 LV.setObjCArray(E->getType()->isArrayType());
1072 if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) {
1073 if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
1074 if (VD->hasGlobalStorage()) {
1075 LV.setGlobalObjCRef(true);
1076 LV.setThreadLocalRef(VD->isThreadSpecified());
1079 LV.setObjCArray(E->getType()->isArrayType());
1083 if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) {
1084 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1088 if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) {
1089 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1090 if (LV.isObjCIvar()) {
1091 // If cast is to a structure pointer, follow gcc's behavior and make it
1092 // a non-ivar write-barrier.
1093 QualType ExpTy = E->getType();
1094 if (ExpTy->isPointerType())
1095 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1096 if (ExpTy->isRecordType())
1097 LV.setObjCIvar(false);
1102 if (const GenericSelectionExpr *Exp = dyn_cast<GenericSelectionExpr>(E)) {
1103 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1107 if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) {
1108 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1112 if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) {
1113 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1117 if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
1118 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1119 if (LV.isObjCIvar() && !LV.isObjCArray())
1120 // Using array syntax to assigning to what an ivar points to is not
1121 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
1122 LV.setObjCIvar(false);
1123 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1124 // Using array syntax to assigning to what global points to is not
1125 // same as assigning to the global itself. {id *G;} G[i] = 0;
1126 LV.setGlobalObjCRef(false);
1130 if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) {
1131 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1132 // We don't know if member is an 'ivar', but this flag is looked at
1133 // only in the context of LV.isObjCIvar().
1134 LV.setObjCArray(E->getType()->isArrayType());
1139 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1140 const Expr *E, const VarDecl *VD) {
1141 assert((VD->hasExternalStorage() || VD->isFileVarDecl()) &&
1142 "Var decl must have external storage or be a file var decl!");
1144 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
1145 if (VD->getType()->isReferenceType())
1146 V = CGF.Builder.CreateLoad(V, "tmp");
1147 unsigned Alignment = CGF.getContext().getDeclAlign(VD).getQuantity();
1148 LValue LV = CGF.MakeAddrLValue(V, E->getType(), Alignment);
1149 setObjCGCLValueClass(CGF.getContext(), E, LV);
1153 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
1154 const Expr *E, const FunctionDecl *FD) {
1155 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
1156 if (!FD->hasPrototype()) {
1157 if (const FunctionProtoType *Proto =
1158 FD->getType()->getAs<FunctionProtoType>()) {
1159 // Ugly case: for a K&R-style definition, the type of the definition
1160 // isn't the same as the type of a use. Correct for this with a
1162 QualType NoProtoType =
1163 CGF.getContext().getFunctionNoProtoType(Proto->getResultType());
1164 NoProtoType = CGF.getContext().getPointerType(NoProtoType);
1165 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType), "tmp");
1168 unsigned Alignment = CGF.getContext().getDeclAlign(FD).getQuantity();
1169 return CGF.MakeAddrLValue(V, E->getType(), Alignment);
1172 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
1173 const NamedDecl *ND = E->getDecl();
1174 unsigned Alignment = getContext().getDeclAlign(ND).getQuantity();
1176 if (ND->hasAttr<WeakRefAttr>()) {
1177 const ValueDecl *VD = cast<ValueDecl>(ND);
1178 llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
1179 return MakeAddrLValue(Aliasee, E->getType(), Alignment);
1182 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1184 // Check if this is a global variable.
1185 if (VD->hasExternalStorage() || VD->isFileVarDecl())
1186 return EmitGlobalVarDeclLValue(*this, E, VD);
1188 bool NonGCable = VD->hasLocalStorage() &&
1189 !VD->getType()->isReferenceType() &&
1190 !VD->hasAttr<BlocksAttr>();
1192 llvm::Value *V = LocalDeclMap[VD];
1193 if (!V && VD->isStaticLocal())
1194 V = CGM.getStaticLocalDeclAddress(VD);
1195 assert(V && "DeclRefExpr not entered in LocalDeclMap?");
1197 if (VD->hasAttr<BlocksAttr>())
1198 V = BuildBlockByrefAddress(V, VD);
1200 if (VD->getType()->isReferenceType())
1201 V = Builder.CreateLoad(V, "tmp");
1203 LValue LV = MakeAddrLValue(V, E->getType(), Alignment);
1205 LV.getQuals().removeObjCGCAttr();
1208 setObjCGCLValueClass(getContext(), E, LV);
1212 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND))
1213 return EmitFunctionDeclLValue(*this, E, fn);
1215 assert(false && "Unhandled DeclRefExpr");
1217 // an invalid LValue, but the assert will
1218 // ensure that this point is never reached.
1222 LValue CodeGenFunction::EmitBlockDeclRefLValue(const BlockDeclRefExpr *E) {
1223 unsigned Alignment =
1224 getContext().getDeclAlign(E->getDecl()).getQuantity();
1225 return MakeAddrLValue(GetAddrOfBlockDecl(E), E->getType(), Alignment);
1228 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
1229 // __extension__ doesn't affect lvalue-ness.
1230 if (E->getOpcode() == UO_Extension)
1231 return EmitLValue(E->getSubExpr());
1233 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
1234 switch (E->getOpcode()) {
1235 default: assert(0 && "Unknown unary operator lvalue!");
1237 QualType T = E->getSubExpr()->getType()->getPointeeType();
1238 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
1240 LValue LV = MakeAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
1241 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
1243 // We should not generate __weak write barrier on indirect reference
1244 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
1245 // But, we continue to generate __strong write barrier on indirect write
1246 // into a pointer to object.
1247 if (getContext().getLangOptions().ObjC1 &&
1248 getContext().getLangOptions().getGCMode() != LangOptions::NonGC &&
1250 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
1255 LValue LV = EmitLValue(E->getSubExpr());
1256 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
1257 llvm::Value *Addr = LV.getAddress();
1259 // real and imag are valid on scalars. This is a faster way of
1261 if (!cast<llvm::PointerType>(Addr->getType())
1262 ->getElementType()->isStructTy()) {
1263 assert(E->getSubExpr()->getType()->isArithmeticType());
1267 assert(E->getSubExpr()->getType()->isAnyComplexType());
1269 unsigned Idx = E->getOpcode() == UO_Imag;
1270 return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(),
1276 LValue LV = EmitLValue(E->getSubExpr());
1277 bool isInc = E->getOpcode() == UO_PreInc;
1279 if (E->getType()->isAnyComplexType())
1280 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
1282 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
1288 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
1289 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
1293 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
1294 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
1299 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
1300 switch (E->getIdentType()) {
1302 return EmitUnsupportedLValue(E, "predefined expression");
1304 case PredefinedExpr::Func:
1305 case PredefinedExpr::Function:
1306 case PredefinedExpr::PrettyFunction: {
1307 unsigned Type = E->getIdentType();
1308 std::string GlobalVarName;
1311 default: assert(0 && "Invalid type");
1312 case PredefinedExpr::Func:
1313 GlobalVarName = "__func__.";
1315 case PredefinedExpr::Function:
1316 GlobalVarName = "__FUNCTION__.";
1318 case PredefinedExpr::PrettyFunction:
1319 GlobalVarName = "__PRETTY_FUNCTION__.";
1323 llvm::StringRef FnName = CurFn->getName();
1324 if (FnName.startswith("\01"))
1325 FnName = FnName.substr(1);
1326 GlobalVarName += FnName;
1328 const Decl *CurDecl = CurCodeDecl;
1330 CurDecl = getContext().getTranslationUnitDecl();
1332 std::string FunctionName =
1333 (isa<BlockDecl>(CurDecl)
1335 : PredefinedExpr::ComputeName((PredefinedExpr::IdentType)Type, CurDecl));
1338 CGM.GetAddrOfConstantCString(FunctionName, GlobalVarName.c_str());
1339 return MakeAddrLValue(C, E->getType());
1344 llvm::BasicBlock *CodeGenFunction::getTrapBB() {
1345 const CodeGenOptions &GCO = CGM.getCodeGenOpts();
1347 // If we are not optimzing, don't collapse all calls to trap in the function
1348 // to the same call, that way, in the debugger they can see which operation
1349 // did in fact fail. If we are optimizing, we collapse all calls to trap down
1350 // to just one per function to save on codesize.
1351 if (GCO.OptimizationLevel && TrapBB)
1354 llvm::BasicBlock *Cont = 0;
1355 if (HaveInsertPoint()) {
1356 Cont = createBasicBlock("cont");
1359 TrapBB = createBasicBlock("trap");
1362 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap, 0, 0);
1363 llvm::CallInst *TrapCall = Builder.CreateCall(F);
1364 TrapCall->setDoesNotReturn();
1365 TrapCall->setDoesNotThrow();
1366 Builder.CreateUnreachable();
1373 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
1374 /// array to pointer, return the array subexpression.
1375 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
1376 // If this isn't just an array->pointer decay, bail out.
1377 const CastExpr *CE = dyn_cast<CastExpr>(E);
1378 if (CE == 0 || CE->getCastKind() != CK_ArrayToPointerDecay)
1381 // If this is a decay from variable width array, bail out.
1382 const Expr *SubExpr = CE->getSubExpr();
1383 if (SubExpr->getType()->isVariableArrayType())
1389 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
1390 // The index must always be an integer, which is not an aggregate. Emit it.
1391 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
1392 QualType IdxTy = E->getIdx()->getType();
1393 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
1395 // If the base is a vector type, then we are forming a vector element lvalue
1396 // with this subscript.
1397 if (E->getBase()->getType()->isVectorType()) {
1398 // Emit the vector as an lvalue to get its address.
1399 LValue LHS = EmitLValue(E->getBase());
1400 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
1401 Idx = Builder.CreateIntCast(Idx, Int32Ty, IdxSigned, "vidx");
1402 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
1403 E->getBase()->getType().getCVRQualifiers());
1406 // Extend or truncate the index type to 32 or 64-bits.
1407 if (Idx->getType() != IntPtrTy)
1408 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
1410 // FIXME: As llvm implements the object size checking, this can come out.
1411 if (CatchUndefined) {
1412 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E->getBase())){
1413 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1414 if (ICE->getCastKind() == CK_ArrayToPointerDecay) {
1415 if (const ConstantArrayType *CAT
1416 = getContext().getAsConstantArrayType(DRE->getType())) {
1417 llvm::APInt Size = CAT->getSize();
1418 llvm::BasicBlock *Cont = createBasicBlock("cont");
1419 Builder.CreateCondBr(Builder.CreateICmpULE(Idx,
1420 llvm::ConstantInt::get(Idx->getType(), Size)),
1429 // We know that the pointer points to a type of the correct size, unless the
1430 // size is a VLA or Objective-C interface.
1431 llvm::Value *Address = 0;
1432 unsigned ArrayAlignment = 0;
1433 if (const VariableArrayType *VAT =
1434 getContext().getAsVariableArrayType(E->getType())) {
1435 llvm::Value *VLASize = GetVLASize(VAT);
1437 Idx = Builder.CreateMul(Idx, VLASize);
1439 // The base must be a pointer, which is not an aggregate. Emit it.
1440 llvm::Value *Base = EmitScalarExpr(E->getBase());
1442 Address = EmitCastToVoidPtr(Base);
1443 if (getContext().getLangOptions().isSignedOverflowDefined())
1444 Address = Builder.CreateGEP(Address, Idx, "arrayidx");
1446 Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
1447 Address = Builder.CreateBitCast(Address, Base->getType());
1448 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
1449 // Indexing over an interface, as in "NSString *P; P[4];"
1450 llvm::Value *InterfaceSize =
1451 llvm::ConstantInt::get(Idx->getType(),
1452 getContext().getTypeSizeInChars(OIT).getQuantity());
1454 Idx = Builder.CreateMul(Idx, InterfaceSize);
1456 // The base must be a pointer, which is not an aggregate. Emit it.
1457 llvm::Value *Base = EmitScalarExpr(E->getBase());
1458 Address = EmitCastToVoidPtr(Base);
1459 Address = Builder.CreateGEP(Address, Idx, "arrayidx");
1460 Address = Builder.CreateBitCast(Address, Base->getType());
1461 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
1462 // If this is A[i] where A is an array, the frontend will have decayed the
1463 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
1464 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
1465 // "gep x, i" here. Emit one "gep A, 0, i".
1466 assert(Array->getType()->isArrayType() &&
1467 "Array to pointer decay must have array source type!");
1468 LValue ArrayLV = EmitLValue(Array);
1469 llvm::Value *ArrayPtr = ArrayLV.getAddress();
1470 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
1471 llvm::Value *Args[] = { Zero, Idx };
1473 // Propagate the alignment from the array itself to the result.
1474 ArrayAlignment = ArrayLV.getAlignment();
1476 if (getContext().getLangOptions().isSignedOverflowDefined())
1477 Address = Builder.CreateGEP(ArrayPtr, Args, Args+2, "arrayidx");
1479 Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, Args+2, "arrayidx");
1481 // The base must be a pointer, which is not an aggregate. Emit it.
1482 llvm::Value *Base = EmitScalarExpr(E->getBase());
1483 if (getContext().getLangOptions().isSignedOverflowDefined())
1484 Address = Builder.CreateGEP(Base, Idx, "arrayidx");
1486 Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
1489 QualType T = E->getBase()->getType()->getPointeeType();
1490 assert(!T.isNull() &&
1491 "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
1493 // Limit the alignment to that of the result type.
1494 if (ArrayAlignment) {
1495 unsigned Align = getContext().getTypeAlignInChars(T).getQuantity();
1496 ArrayAlignment = std::min(Align, ArrayAlignment);
1499 LValue LV = MakeAddrLValue(Address, T, ArrayAlignment);
1500 LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
1502 if (getContext().getLangOptions().ObjC1 &&
1503 getContext().getLangOptions().getGCMode() != LangOptions::NonGC) {
1504 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
1505 setObjCGCLValueClass(getContext(), E, LV);
1511 llvm::Constant *GenerateConstantVector(llvm::LLVMContext &VMContext,
1512 llvm::SmallVector<unsigned, 4> &Elts) {
1513 llvm::SmallVector<llvm::Constant*, 4> CElts;
1515 const llvm::Type *Int32Ty = llvm::Type::getInt32Ty(VMContext);
1516 for (unsigned i = 0, e = Elts.size(); i != e; ++i)
1517 CElts.push_back(llvm::ConstantInt::get(Int32Ty, Elts[i]));
1519 return llvm::ConstantVector::get(CElts);
1522 LValue CodeGenFunction::
1523 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
1524 // Emit the base vector as an l-value.
1527 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
1529 // If it is a pointer to a vector, emit the address and form an lvalue with
1531 llvm::Value *Ptr = EmitScalarExpr(E->getBase());
1532 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
1533 Base = MakeAddrLValue(Ptr, PT->getPointeeType());
1534 Base.getQuals().removeObjCGCAttr();
1535 } else if (E->getBase()->isGLValue()) {
1536 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
1537 // emit the base as an lvalue.
1538 assert(E->getBase()->getType()->isVectorType());
1539 Base = EmitLValue(E->getBase());
1541 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
1542 assert(E->getBase()->getType()->getAs<VectorType>() &&
1543 "Result must be a vector");
1544 llvm::Value *Vec = EmitScalarExpr(E->getBase());
1546 // Store the vector to memory (because LValue wants an address).
1547 llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
1548 Builder.CreateStore(Vec, VecMem);
1549 Base = MakeAddrLValue(VecMem, E->getBase()->getType());
1552 // Encode the element access list into a vector of unsigned indices.
1553 llvm::SmallVector<unsigned, 4> Indices;
1554 E->getEncodedElementAccess(Indices);
1556 if (Base.isSimple()) {
1557 llvm::Constant *CV = GenerateConstantVector(getLLVMContext(), Indices);
1558 return LValue::MakeExtVectorElt(Base.getAddress(), CV,
1559 Base.getVRQualifiers());
1561 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
1563 llvm::Constant *BaseElts = Base.getExtVectorElts();
1564 llvm::SmallVector<llvm::Constant *, 4> CElts;
1566 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1567 if (isa<llvm::ConstantAggregateZero>(BaseElts))
1568 CElts.push_back(llvm::ConstantInt::get(Int32Ty, 0));
1570 CElts.push_back(cast<llvm::Constant>(BaseElts->getOperand(Indices[i])));
1572 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
1573 return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV,
1574 Base.getVRQualifiers());
1577 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
1578 bool isNonGC = false;
1579 Expr *BaseExpr = E->getBase();
1580 llvm::Value *BaseValue = NULL;
1581 Qualifiers BaseQuals;
1583 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
1585 BaseValue = EmitScalarExpr(BaseExpr);
1586 const PointerType *PTy =
1587 BaseExpr->getType()->getAs<PointerType>();
1588 BaseQuals = PTy->getPointeeType().getQualifiers();
1590 LValue BaseLV = EmitLValue(BaseExpr);
1591 if (BaseLV.isNonGC())
1593 // FIXME: this isn't right for bitfields.
1594 BaseValue = BaseLV.getAddress();
1595 QualType BaseTy = BaseExpr->getType();
1596 BaseQuals = BaseTy.getQualifiers();
1599 NamedDecl *ND = E->getMemberDecl();
1600 if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) {
1601 LValue LV = EmitLValueForField(BaseValue, Field,
1602 BaseQuals.getCVRQualifiers());
1603 LV.setNonGC(isNonGC);
1604 setObjCGCLValueClass(getContext(), E, LV);
1608 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
1609 return EmitGlobalVarDeclLValue(*this, E, VD);
1611 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
1612 return EmitFunctionDeclLValue(*this, E, FD);
1614 assert(false && "Unhandled member declaration!");
1618 LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value *BaseValue,
1619 const FieldDecl *Field,
1620 unsigned CVRQualifiers) {
1621 const CGRecordLayout &RL =
1622 CGM.getTypes().getCGRecordLayout(Field->getParent());
1623 const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field);
1624 return LValue::MakeBitfield(BaseValue, Info,
1625 Field->getType().getCVRQualifiers()|CVRQualifiers);
1628 /// EmitLValueForAnonRecordField - Given that the field is a member of
1629 /// an anonymous struct or union buried inside a record, and given
1630 /// that the base value is a pointer to the enclosing record, derive
1631 /// an lvalue for the ultimate field.
1632 LValue CodeGenFunction::EmitLValueForAnonRecordField(llvm::Value *BaseValue,
1633 const IndirectFieldDecl *Field,
1634 unsigned CVRQualifiers) {
1635 IndirectFieldDecl::chain_iterator I = Field->chain_begin(),
1636 IEnd = Field->chain_end();
1638 LValue LV = EmitLValueForField(BaseValue, cast<FieldDecl>(*I),
1640 if (++I == IEnd) return LV;
1642 assert(LV.isSimple());
1643 BaseValue = LV.getAddress();
1644 CVRQualifiers |= LV.getVRQualifiers();
1648 LValue CodeGenFunction::EmitLValueForField(llvm::Value *baseAddr,
1649 const FieldDecl *field,
1651 if (field->isBitField())
1652 return EmitLValueForBitfield(baseAddr, field, cvr);
1654 const RecordDecl *rec = field->getParent();
1655 QualType type = field->getType();
1657 bool mayAlias = rec->hasAttr<MayAliasAttr>();
1660 if (rec->isUnion()) {
1661 // For unions, we just cast to the appropriate type.
1662 assert(!type->isReferenceType() && "union has reference member");
1664 const llvm::Type *llvmType = CGM.getTypes().ConvertTypeForMem(type);
1666 cast<llvm::PointerType>(baseAddr->getType())->getAddressSpace();
1667 addr = Builder.CreateBitCast(baseAddr, llvmType->getPointerTo(AS),
1670 // For structs, we GEP to the field that the record layout suggests.
1671 unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
1672 addr = Builder.CreateStructGEP(baseAddr, idx, field->getName());
1674 // If this is a reference field, load the reference right now.
1675 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
1676 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
1677 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
1679 if (CGM.shouldUseTBAA()) {
1682 tbaa = CGM.getTBAAInfo(getContext().CharTy);
1684 tbaa = CGM.getTBAAInfo(type);
1685 CGM.DecorateInstruction(load, tbaa);
1690 type = refType->getPointeeType();
1691 cvr = 0; // qualifiers don't recursively apply to referencee
1695 unsigned alignment = getContext().getDeclAlign(field).getQuantity();
1696 LValue LV = MakeAddrLValue(addr, type, alignment);
1697 LV.getQuals().addCVRQualifiers(cvr);
1699 // __weak attribute on a field is ignored.
1700 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
1701 LV.getQuals().removeObjCGCAttr();
1703 // Fields of may_alias structs act like 'char' for TBAA purposes.
1704 // FIXME: this should get propagated down through anonymous structs
1706 if (mayAlias && LV.getTBAAInfo())
1707 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
1713 CodeGenFunction::EmitLValueForFieldInitialization(llvm::Value *BaseValue,
1714 const FieldDecl *Field,
1715 unsigned CVRQualifiers) {
1716 QualType FieldType = Field->getType();
1718 if (!FieldType->isReferenceType())
1719 return EmitLValueForField(BaseValue, Field, CVRQualifiers);
1721 const CGRecordLayout &RL =
1722 CGM.getTypes().getCGRecordLayout(Field->getParent());
1723 unsigned idx = RL.getLLVMFieldNo(Field);
1724 llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp");
1726 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
1728 unsigned Alignment = getContext().getDeclAlign(Field).getQuantity();
1729 return MakeAddrLValue(V, FieldType, Alignment);
1732 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
1733 llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
1734 const Expr *InitExpr = E->getInitializer();
1735 LValue Result = MakeAddrLValue(DeclPtr, E->getType());
1737 EmitAnyExprToMem(InitExpr, DeclPtr, /*Volatile*/ false, /*Init*/ true);
1742 LValue CodeGenFunction::
1743 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
1744 if (!expr->isGLValue()) {
1745 // ?: here should be an aggregate.
1746 assert((hasAggregateLLVMType(expr->getType()) &&
1747 !expr->getType()->isAnyComplexType()) &&
1748 "Unexpected conditional operator!");
1749 return EmitAggExprToLValue(expr);
1752 const Expr *condExpr = expr->getCond();
1754 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
1755 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
1756 if (!CondExprBool) std::swap(live, dead);
1758 if (!ContainsLabel(dead))
1759 return EmitLValue(live);
1762 OpaqueValueMapping binding(*this, expr);
1764 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
1765 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
1766 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
1768 ConditionalEvaluation eval(*this);
1769 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock);
1771 // Any temporaries created here are conditional.
1772 EmitBlock(lhsBlock);
1774 LValue lhs = EmitLValue(expr->getTrueExpr());
1777 if (!lhs.isSimple())
1778 return EmitUnsupportedLValue(expr, "conditional operator");
1780 lhsBlock = Builder.GetInsertBlock();
1781 Builder.CreateBr(contBlock);
1783 // Any temporaries created here are conditional.
1784 EmitBlock(rhsBlock);
1786 LValue rhs = EmitLValue(expr->getFalseExpr());
1788 if (!rhs.isSimple())
1789 return EmitUnsupportedLValue(expr, "conditional operator");
1790 rhsBlock = Builder.GetInsertBlock();
1792 EmitBlock(contBlock);
1794 llvm::PHINode *phi = Builder.CreatePHI(lhs.getAddress()->getType(), 2,
1796 phi->addIncoming(lhs.getAddress(), lhsBlock);
1797 phi->addIncoming(rhs.getAddress(), rhsBlock);
1798 return MakeAddrLValue(phi, expr->getType());
1801 /// EmitCastLValue - Casts are never lvalues unless that cast is a dynamic_cast.
1802 /// If the cast is a dynamic_cast, we can have the usual lvalue result,
1803 /// otherwise if a cast is needed by the code generator in an lvalue context,
1804 /// then it must mean that we need the address of an aggregate in order to
1805 /// access one of its fields. This can happen for all the reasons that casts
1806 /// are permitted with aggregate result, including noop aggregate casts, and
1807 /// cast from scalar to union.
1808 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
1809 switch (E->getCastKind()) {
1811 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
1814 llvm_unreachable("dependent cast kind in IR gen!");
1816 case CK_GetObjCProperty: {
1817 LValue LV = EmitLValue(E->getSubExpr());
1818 assert(LV.isPropertyRef());
1819 RValue RV = EmitLoadOfPropertyRefLValue(LV);
1821 // Property is an aggregate r-value.
1822 if (RV.isAggregate()) {
1823 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
1826 // Implicit property returns an l-value.
1827 assert(RV.isScalar());
1828 return MakeAddrLValue(RV.getScalarVal(), E->getSubExpr()->getType());
1832 case CK_LValueToRValue:
1833 if (!E->getSubExpr()->Classify(getContext()).isPRValue()
1834 || E->getType()->isRecordType())
1835 return EmitLValue(E->getSubExpr());
1836 // Fall through to synthesize a temporary.
1839 case CK_ArrayToPointerDecay:
1840 case CK_FunctionToPointerDecay:
1841 case CK_NullToMemberPointer:
1842 case CK_NullToPointer:
1843 case CK_IntegralToPointer:
1844 case CK_PointerToIntegral:
1845 case CK_PointerToBoolean:
1846 case CK_VectorSplat:
1847 case CK_IntegralCast:
1848 case CK_IntegralToBoolean:
1849 case CK_IntegralToFloating:
1850 case CK_FloatingToIntegral:
1851 case CK_FloatingToBoolean:
1852 case CK_FloatingCast:
1853 case CK_FloatingRealToComplex:
1854 case CK_FloatingComplexToReal:
1855 case CK_FloatingComplexToBoolean:
1856 case CK_FloatingComplexCast:
1857 case CK_FloatingComplexToIntegralComplex:
1858 case CK_IntegralRealToComplex:
1859 case CK_IntegralComplexToReal:
1860 case CK_IntegralComplexToBoolean:
1861 case CK_IntegralComplexCast:
1862 case CK_IntegralComplexToFloatingComplex:
1863 case CK_DerivedToBaseMemberPointer:
1864 case CK_BaseToDerivedMemberPointer:
1865 case CK_MemberPointerToBoolean:
1866 case CK_AnyPointerToBlockPointerCast: {
1867 // These casts only produce lvalues when we're binding a reference to a
1868 // temporary realized from a (converted) pure rvalue. Emit the expression
1869 // as a value, copy it into a temporary, and return an lvalue referring to
1871 llvm::Value *V = CreateMemTemp(E->getType(), "ref.temp");
1872 EmitAnyExprToMem(E, V, false, false);
1873 return MakeAddrLValue(V, E->getType());
1877 LValue LV = EmitLValue(E->getSubExpr());
1878 llvm::Value *V = LV.getAddress();
1879 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E);
1880 return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
1883 case CK_ConstructorConversion:
1884 case CK_UserDefinedConversion:
1885 case CK_AnyPointerToObjCPointerCast:
1886 return EmitLValue(E->getSubExpr());
1888 case CK_UncheckedDerivedToBase:
1889 case CK_DerivedToBase: {
1890 const RecordType *DerivedClassTy =
1891 E->getSubExpr()->getType()->getAs<RecordType>();
1892 CXXRecordDecl *DerivedClassDecl =
1893 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1895 LValue LV = EmitLValue(E->getSubExpr());
1896 llvm::Value *This = LV.getAddress();
1898 // Perform the derived-to-base conversion
1900 GetAddressOfBaseClass(This, DerivedClassDecl,
1901 E->path_begin(), E->path_end(),
1902 /*NullCheckValue=*/false);
1904 return MakeAddrLValue(Base, E->getType());
1907 return EmitAggExprToLValue(E);
1908 case CK_BaseToDerived: {
1909 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
1910 CXXRecordDecl *DerivedClassDecl =
1911 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1913 LValue LV = EmitLValue(E->getSubExpr());
1915 // Perform the base-to-derived conversion
1916 llvm::Value *Derived =
1917 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
1918 E->path_begin(), E->path_end(),
1919 /*NullCheckValue=*/false);
1921 return MakeAddrLValue(Derived, E->getType());
1923 case CK_LValueBitCast: {
1924 // This must be a reinterpret_cast (or c-style equivalent).
1925 const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E);
1927 LValue LV = EmitLValue(E->getSubExpr());
1928 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
1929 ConvertType(CE->getTypeAsWritten()));
1930 return MakeAddrLValue(V, E->getType());
1932 case CK_ObjCObjectLValueCast: {
1933 LValue LV = EmitLValue(E->getSubExpr());
1934 QualType ToType = getContext().getLValueReferenceType(E->getType());
1935 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
1936 ConvertType(ToType));
1937 return MakeAddrLValue(V, E->getType());
1941 llvm_unreachable("Unhandled lvalue cast kind?");
1944 LValue CodeGenFunction::EmitNullInitializationLValue(
1945 const CXXScalarValueInitExpr *E) {
1946 QualType Ty = E->getType();
1947 LValue LV = MakeAddrLValue(CreateMemTemp(Ty), Ty);
1948 EmitNullInitialization(LV.getAddress(), Ty);
1952 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
1953 assert(e->isGLValue() || e->getType()->isRecordType());
1954 return getOpaqueLValueMapping(e);
1957 //===--------------------------------------------------------------------===//
1958 // Expression Emission
1959 //===--------------------------------------------------------------------===//
1962 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
1963 ReturnValueSlot ReturnValue) {
1964 if (CGDebugInfo *DI = getDebugInfo()) {
1965 DI->setLocation(E->getLocStart());
1966 DI->UpdateLineDirectiveRegion(Builder);
1967 DI->EmitStopPoint(Builder);
1970 // Builtins never have block type.
1971 if (E->getCallee()->getType()->isBlockPointerType())
1972 return EmitBlockCallExpr(E, ReturnValue);
1974 if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E))
1975 return EmitCXXMemberCallExpr(CE, ReturnValue);
1977 const Decl *TargetDecl = 0;
1978 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E->getCallee())) {
1979 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1980 TargetDecl = DRE->getDecl();
1981 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(TargetDecl))
1982 if (unsigned builtinID = FD->getBuiltinID())
1983 return EmitBuiltinExpr(FD, builtinID, E);
1987 if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E))
1988 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
1989 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
1991 if (isa<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
1992 // C++ [expr.pseudo]p1:
1993 // The result shall only be used as the operand for the function call
1994 // operator (), and the result of such a call has type void. The only
1995 // effect is the evaluation of the postfix-expression before the dot or
1997 EmitScalarExpr(E->getCallee());
1998 return RValue::get(0);
2001 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
2002 return EmitCall(E->getCallee()->getType(), Callee, ReturnValue,
2003 E->arg_begin(), E->arg_end(), TargetDecl);
2006 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
2007 // Comma expressions just emit their LHS then their RHS as an l-value.
2008 if (E->getOpcode() == BO_Comma) {
2009 EmitIgnoredExpr(E->getLHS());
2010 EnsureInsertPoint();
2011 return EmitLValue(E->getRHS());
2014 if (E->getOpcode() == BO_PtrMemD ||
2015 E->getOpcode() == BO_PtrMemI)
2016 return EmitPointerToDataMemberBinaryExpr(E);
2018 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
2020 if (!hasAggregateLLVMType(E->getType())) {
2021 // __block variables need the RHS evaluated first.
2022 RValue RV = EmitAnyExpr(E->getRHS());
2023 LValue LV = EmitLValue(E->getLHS());
2024 EmitStoreThroughLValue(RV, LV, E->getType());
2028 if (E->getType()->isAnyComplexType())
2029 return EmitComplexAssignmentLValue(E);
2031 return EmitAggExprToLValue(E);
2034 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
2035 RValue RV = EmitCallExpr(E);
2038 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2040 assert(E->getCallReturnType()->isReferenceType() &&
2041 "Can't have a scalar return unless the return type is a "
2044 return MakeAddrLValue(RV.getScalarVal(), E->getType());
2047 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
2048 // FIXME: This shouldn't require another copy.
2049 return EmitAggExprToLValue(E);
2052 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
2053 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
2054 && "binding l-value to type which needs a temporary");
2055 AggValueSlot Slot = CreateAggTemp(E->getType(), "tmp");
2056 EmitCXXConstructExpr(E, Slot);
2057 return MakeAddrLValue(Slot.getAddr(), E->getType());
2061 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
2062 return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
2066 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
2067 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
2068 Slot.setLifetimeExternallyManaged();
2069 EmitAggExpr(E->getSubExpr(), Slot);
2070 EmitCXXTemporary(E->getTemporary(), Slot.getAddr());
2071 return MakeAddrLValue(Slot.getAddr(), E->getType());
2074 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
2075 RValue RV = EmitObjCMessageExpr(E);
2078 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2080 assert(E->getMethodDecl()->getResultType()->isReferenceType() &&
2081 "Can't have a scalar return unless the return type is a "
2084 return MakeAddrLValue(RV.getScalarVal(), E->getType());
2087 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
2089 CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true);
2090 return MakeAddrLValue(V, E->getType());
2093 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
2094 const ObjCIvarDecl *Ivar) {
2095 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
2098 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
2099 llvm::Value *BaseValue,
2100 const ObjCIvarDecl *Ivar,
2101 unsigned CVRQualifiers) {
2102 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
2103 Ivar, CVRQualifiers);
2106 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
2107 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
2108 llvm::Value *BaseValue = 0;
2109 const Expr *BaseExpr = E->getBase();
2110 Qualifiers BaseQuals;
2113 BaseValue = EmitScalarExpr(BaseExpr);
2114 ObjectTy = BaseExpr->getType()->getPointeeType();
2115 BaseQuals = ObjectTy.getQualifiers();
2117 LValue BaseLV = EmitLValue(BaseExpr);
2118 // FIXME: this isn't right for bitfields.
2119 BaseValue = BaseLV.getAddress();
2120 ObjectTy = BaseExpr->getType();
2121 BaseQuals = ObjectTy.getQualifiers();
2125 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
2126 BaseQuals.getCVRQualifiers());
2127 setObjCGCLValueClass(getContext(), E, LV);
2131 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
2132 // Can only get l-value for message expression returning aggregate type
2133 RValue RV = EmitAnyExprToTemp(E);
2134 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2137 RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
2138 ReturnValueSlot ReturnValue,
2139 CallExpr::const_arg_iterator ArgBeg,
2140 CallExpr::const_arg_iterator ArgEnd,
2141 const Decl *TargetDecl) {
2142 // Get the actual function type. The callee type will always be a pointer to
2143 // function type or a block pointer type.
2144 assert(CalleeType->isFunctionPointerType() &&
2145 "Call must have function pointer type!");
2147 CalleeType = getContext().getCanonicalType(CalleeType);
2149 const FunctionType *FnType
2150 = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
2153 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd);
2155 return EmitCall(CGM.getTypes().getFunctionInfo(Args, FnType),
2156 Callee, ReturnValue, Args, TargetDecl);
2159 LValue CodeGenFunction::
2160 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
2162 if (E->getOpcode() == BO_PtrMemI)
2163 BaseV = EmitScalarExpr(E->getLHS());
2165 BaseV = EmitLValue(E->getLHS()).getAddress();
2167 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
2169 const MemberPointerType *MPT
2170 = E->getRHS()->getType()->getAs<MemberPointerType>();
2173 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, BaseV, OffsetV, MPT);
2175 return MakeAddrLValue(AddV, MPT->getPointeeType());