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 "CGObjCRuntime.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "llvm/Target/TargetData.h"
21 using namespace clang;
22 using namespace CodeGen;
23 
24 //===--------------------------------------------------------------------===//
25 //                        Miscellaneous Helper Methods
26 //===--------------------------------------------------------------------===//
27 
28 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
29 /// block.
30 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
31                                                     const char *Name) {
32   if (!Builder.isNamePreserving())
33     Name = "";
34   return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
35 }
36 
37 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
38 /// expression and compare the result against zero, returning an Int1Ty value.
39 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
40   QualType BoolTy = getContext().BoolTy;
41   if (!E->getType()->isAnyComplexType())
42     return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
43 
44   return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
45 }
46 
47 /// EmitAnyExpr - Emit code to compute the specified expression which can have
48 /// any type.  The result is returned as an RValue struct.  If this is an
49 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where the
50 /// result should be returned.
51 RValue CodeGenFunction::EmitAnyExpr(const Expr *E, llvm::Value *AggLoc,
52                                     bool IsAggLocVolatile, bool IgnoreResult,
53                                     bool IsInitializer) {
54   if (!hasAggregateLLVMType(E->getType()))
55     return RValue::get(EmitScalarExpr(E, IgnoreResult));
56   else if (E->getType()->isAnyComplexType())
57     return RValue::getComplex(EmitComplexExpr(E, false, false,
58                                               IgnoreResult, IgnoreResult));
59 
60   EmitAggExpr(E, AggLoc, IsAggLocVolatile, IgnoreResult, IsInitializer);
61   return RValue::getAggregate(AggLoc, IsAggLocVolatile);
62 }
63 
64 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
65 /// always be accessible even if no aggregate location is provided.
66 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E,
67                                           bool IsAggLocVolatile,
68                                           bool IsInitializer) {
69   llvm::Value *AggLoc = 0;
70 
71   if (hasAggregateLLVMType(E->getType()) &&
72       !E->getType()->isAnyComplexType())
73     AggLoc = CreateTempAlloca(ConvertType(E->getType()), "agg.tmp");
74   return EmitAnyExpr(E, AggLoc, IsAggLocVolatile, /*IgnoreResult=*/false,
75                      IsInitializer);
76 }
77 
78 RValue CodeGenFunction::EmitReferenceBindingToExpr(const Expr* E,
79                                                    QualType DestType,
80                                                    bool IsInitializer) {
81   RValue Val;
82   if (E->isLvalue(getContext()) == Expr::LV_Valid) {
83     // Emit the expr as an lvalue.
84     LValue LV = EmitLValue(E);
85     if (LV.isSimple())
86       return RValue::get(LV.getAddress());
87     Val = EmitLoadOfLValue(LV, E->getType());
88   } else {
89     // FIXME: Initializers don't work with casts yet. For example
90     // const A& a = B();
91     // if B inherits from A.
92     Val = EmitAnyExprToTemp(E, /*IsAggLocVolatile=*/false,
93                             IsInitializer);
94 
95     if (IsInitializer) {
96       // We might have to destroy the temporary variable.
97       if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
98         if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
99           if (!ClassDecl->hasTrivialDestructor()) {
100             const CXXDestructorDecl *Dtor =
101               ClassDecl->getDestructor(getContext());
102 
103             CleanupScope scope(*this);
104             EmitCXXDestructorCall(Dtor, Dtor_Complete, Val.getAggregateAddr());
105           }
106         }
107       }
108     }
109   }
110 
111   if (Val.isAggregate()) {
112     Val = RValue::get(Val.getAggregateAddr());
113   } else {
114     // Create a temporary variable that we can bind the reference to.
115     llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(E->getType()),
116                                          "reftmp");
117     if (Val.isScalar())
118       EmitStoreOfScalar(Val.getScalarVal(), Temp, false, E->getType());
119     else
120       StoreComplexToAddr(Val.getComplexVal(), Temp, false);
121     Val = RValue::get(Temp);
122   }
123 
124   return Val;
125 }
126 
127 
128 /// getAccessedFieldNo - Given an encoded value and a result number, return the
129 /// input field number being accessed.
130 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
131                                              const llvm::Constant *Elts) {
132   if (isa<llvm::ConstantAggregateZero>(Elts))
133     return 0;
134 
135   return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue();
136 }
137 
138 
139 //===----------------------------------------------------------------------===//
140 //                         LValue Expression Emission
141 //===----------------------------------------------------------------------===//
142 
143 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
144   if (Ty->isVoidType()) {
145     return RValue::get(0);
146   } else if (const ComplexType *CTy = Ty->getAsComplexType()) {
147     const llvm::Type *EltTy = ConvertType(CTy->getElementType());
148     llvm::Value *U = llvm::UndefValue::get(EltTy);
149     return RValue::getComplex(std::make_pair(U, U));
150   } else if (hasAggregateLLVMType(Ty)) {
151     const llvm::Type *LTy = llvm::PointerType::getUnqual(ConvertType(Ty));
152     return RValue::getAggregate(llvm::UndefValue::get(LTy));
153   } else {
154     return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
155   }
156 }
157 
158 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
159                                               const char *Name) {
160   ErrorUnsupported(E, Name);
161   return GetUndefRValue(E->getType());
162 }
163 
164 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
165                                               const char *Name) {
166   ErrorUnsupported(E, Name);
167   llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
168   return LValue::MakeAddr(llvm::UndefValue::get(Ty),
169                           E->getType().getCVRQualifiers(),
170                           getContext().getObjCGCAttrKind(E->getType()),
171                           E->getType().getAddressSpace());
172 }
173 
174 /// EmitLValue - Emit code to compute a designator that specifies the location
175 /// of the expression.
176 ///
177 /// This can return one of two things: a simple address or a bitfield reference.
178 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
179 /// an LLVM pointer type.
180 ///
181 /// If this returns a bitfield reference, nothing about the pointee type of the
182 /// LLVM value is known: For example, it may not be a pointer to an integer.
183 ///
184 /// If this returns a normal address, and if the lvalue's C type is fixed size,
185 /// this method guarantees that the returned pointer type will point to an LLVM
186 /// type of the same size of the lvalue's type.  If the lvalue has a variable
187 /// length type, this is not possible.
188 ///
189 LValue CodeGenFunction::EmitLValue(const Expr *E) {
190   switch (E->getStmtClass()) {
191   default: return EmitUnsupportedLValue(E, "l-value expression");
192 
193   case Expr::BinaryOperatorClass:
194     return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
195   case Expr::CallExprClass:
196   case Expr::CXXMemberCallExprClass:
197   case Expr::CXXOperatorCallExprClass:
198     return EmitCallExprLValue(cast<CallExpr>(E));
199   case Expr::VAArgExprClass:
200     return EmitVAArgExprLValue(cast<VAArgExpr>(E));
201   case Expr::DeclRefExprClass:
202   case Expr::QualifiedDeclRefExprClass:
203     return EmitDeclRefLValue(cast<DeclRefExpr>(E));
204   case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
205   case Expr::PredefinedExprClass:
206     return EmitPredefinedLValue(cast<PredefinedExpr>(E));
207   case Expr::StringLiteralClass:
208     return EmitStringLiteralLValue(cast<StringLiteral>(E));
209   case Expr::ObjCEncodeExprClass:
210     return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
211 
212   case Expr::BlockDeclRefExprClass:
213     return EmitBlockDeclRefLValue(cast<BlockDeclRefExpr>(E));
214 
215   case Expr::CXXConditionDeclExprClass:
216     return EmitCXXConditionDeclLValue(cast<CXXConditionDeclExpr>(E));
217   case Expr::CXXTemporaryObjectExprClass:
218   case Expr::CXXConstructExprClass:
219     return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
220   case Expr::CXXBindTemporaryExprClass:
221     return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
222 
223   case Expr::ObjCMessageExprClass:
224     return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
225   case Expr::ObjCIvarRefExprClass:
226     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
227   case Expr::ObjCPropertyRefExprClass:
228     return EmitObjCPropertyRefLValue(cast<ObjCPropertyRefExpr>(E));
229   case Expr::ObjCImplicitSetterGetterRefExprClass:
230     return EmitObjCKVCRefLValue(cast<ObjCImplicitSetterGetterRefExpr>(E));
231   case Expr::ObjCSuperExprClass:
232     return EmitObjCSuperExprLValue(cast<ObjCSuperExpr>(E));
233 
234   case Expr::StmtExprClass:
235     return EmitStmtExprLValue(cast<StmtExpr>(E));
236   case Expr::UnaryOperatorClass:
237     return EmitUnaryOpLValue(cast<UnaryOperator>(E));
238   case Expr::ArraySubscriptExprClass:
239     return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
240   case Expr::ExtVectorElementExprClass:
241     return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
242   case Expr::MemberExprClass:
243     return EmitMemberExpr(cast<MemberExpr>(E));
244   case Expr::CompoundLiteralExprClass:
245     return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
246   case Expr::ConditionalOperatorClass:
247     return EmitConditionalOperator(cast<ConditionalOperator>(E));
248   case Expr::ChooseExprClass:
249     return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext()));
250   case Expr::ImplicitCastExprClass:
251   case Expr::CStyleCastExprClass:
252   case Expr::CXXFunctionalCastExprClass:
253   case Expr::CXXStaticCastExprClass:
254   case Expr::CXXDynamicCastExprClass:
255   case Expr::CXXReinterpretCastExprClass:
256   case Expr::CXXConstCastExprClass:
257     return EmitCastLValue(cast<CastExpr>(E));
258   }
259 }
260 
261 llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
262                                                QualType Ty) {
263   llvm::Value *V = Builder.CreateLoad(Addr, Volatile, "tmp");
264 
265   // Bool can have different representation in memory than in registers.
266   if (Ty->isBooleanType())
267     if (V->getType() != llvm::Type::getInt1Ty(VMContext))
268       V = Builder.CreateTrunc(V, llvm::Type::getInt1Ty(VMContext), "tobool");
269 
270   return V;
271 }
272 
273 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
274                                         bool Volatile, QualType Ty) {
275 
276   if (Ty->isBooleanType()) {
277     // Bool can have different representation in memory than in registers.
278     const llvm::Type *SrcTy = Value->getType();
279     const llvm::PointerType *DstPtr = cast<llvm::PointerType>(Addr->getType());
280     if (DstPtr->getElementType() != SrcTy) {
281       const llvm::Type *MemTy =
282         llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace());
283       Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp");
284     }
285   }
286   Builder.CreateStore(Value, Addr, Volatile);
287 }
288 
289 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
290 /// method emits the address of the lvalue, then loads the result as an rvalue,
291 /// returning the rvalue.
292 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
293   if (LV.isObjCWeak()) {
294     // load of a __weak object.
295     llvm::Value *AddrWeakObj = LV.getAddress();
296     llvm::Value *read_weak = CGM.getObjCRuntime().EmitObjCWeakRead(*this,
297                                                                    AddrWeakObj);
298     return RValue::get(read_weak);
299   }
300 
301   if (LV.isSimple()) {
302     llvm::Value *Ptr = LV.getAddress();
303     const llvm::Type *EltTy =
304       cast<llvm::PointerType>(Ptr->getType())->getElementType();
305 
306     // Simple scalar l-value.
307     if (EltTy->isSingleValueType())
308       return RValue::get(EmitLoadOfScalar(Ptr, LV.isVolatileQualified(),
309                                           ExprType));
310 
311     assert(ExprType->isFunctionType() && "Unknown scalar value");
312     return RValue::get(Ptr);
313   }
314 
315   if (LV.isVectorElt()) {
316     llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(),
317                                           LV.isVolatileQualified(), "tmp");
318     return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
319                                                     "vecext"));
320   }
321 
322   // If this is a reference to a subset of the elements of a vector, either
323   // shuffle the input or extract/insert them as appropriate.
324   if (LV.isExtVectorElt())
325     return EmitLoadOfExtVectorElementLValue(LV, ExprType);
326 
327   if (LV.isBitfield())
328     return EmitLoadOfBitfieldLValue(LV, ExprType);
329 
330   if (LV.isPropertyRef())
331     return EmitLoadOfPropertyRefLValue(LV, ExprType);
332 
333   assert(LV.isKVCRef() && "Unknown LValue type!");
334   return EmitLoadOfKVCRefLValue(LV, ExprType);
335 }
336 
337 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
338                                                  QualType ExprType) {
339   unsigned StartBit = LV.getBitfieldStartBit();
340   unsigned BitfieldSize = LV.getBitfieldSize();
341   llvm::Value *Ptr = LV.getBitfieldAddr();
342 
343   const llvm::Type *EltTy =
344     cast<llvm::PointerType>(Ptr->getType())->getElementType();
345   unsigned EltTySize = CGM.getTargetData().getTypeSizeInBits(EltTy);
346 
347   // In some cases the bitfield may straddle two memory locations.  Currently we
348   // load the entire bitfield, then do the magic to sign-extend it if
349   // necessary. This results in somewhat more code than necessary for the common
350   // case (one load), since two shifts accomplish both the masking and sign
351   // extension.
352   unsigned LowBits = std::min(BitfieldSize, EltTySize - StartBit);
353   llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "tmp");
354 
355   // Shift to proper location.
356   if (StartBit)
357     Val = Builder.CreateLShr(Val, llvm::ConstantInt::get(EltTy, StartBit),
358                              "bf.lo");
359 
360   // Mask off unused bits.
361   llvm::Constant *LowMask = llvm::ConstantInt::get(VMContext,
362                                 llvm::APInt::getLowBitsSet(EltTySize, LowBits));
363   Val = Builder.CreateAnd(Val, LowMask, "bf.lo.cleared");
364 
365   // Fetch the high bits if necessary.
366   if (LowBits < BitfieldSize) {
367     unsigned HighBits = BitfieldSize - LowBits;
368     llvm::Value *HighPtr = Builder.CreateGEP(Ptr, llvm::ConstantInt::get(
369                             llvm::Type::getInt32Ty(VMContext), 1), "bf.ptr.hi");
370     llvm::Value *HighVal = Builder.CreateLoad(HighPtr,
371                                               LV.isVolatileQualified(),
372                                               "tmp");
373 
374     // Mask off unused bits.
375     llvm::Constant *HighMask = llvm::ConstantInt::get(VMContext,
376                                llvm::APInt::getLowBitsSet(EltTySize, HighBits));
377     HighVal = Builder.CreateAnd(HighVal, HighMask, "bf.lo.cleared");
378 
379     // Shift to proper location and or in to bitfield value.
380     HighVal = Builder.CreateShl(HighVal,
381                                 llvm::ConstantInt::get(EltTy, LowBits));
382     Val = Builder.CreateOr(Val, HighVal, "bf.val");
383   }
384 
385   // Sign extend if necessary.
386   if (LV.isBitfieldSigned()) {
387     llvm::Value *ExtraBits = llvm::ConstantInt::get(EltTy,
388                                                     EltTySize - BitfieldSize);
389     Val = Builder.CreateAShr(Builder.CreateShl(Val, ExtraBits),
390                              ExtraBits, "bf.val.sext");
391   }
392 
393   // The bitfield type and the normal type differ when the storage sizes differ
394   // (currently just _Bool).
395   Val = Builder.CreateIntCast(Val, ConvertType(ExprType), false, "tmp");
396 
397   return RValue::get(Val);
398 }
399 
400 RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
401                                                     QualType ExprType) {
402   return EmitObjCPropertyGet(LV.getPropertyRefExpr());
403 }
404 
405 RValue CodeGenFunction::EmitLoadOfKVCRefLValue(LValue LV,
406                                                QualType ExprType) {
407   return EmitObjCPropertyGet(LV.getKVCRefExpr());
408 }
409 
410 // If this is a reference to a subset of the elements of a vector, create an
411 // appropriate shufflevector.
412 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV,
413                                                          QualType ExprType) {
414   llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(),
415                                         LV.isVolatileQualified(), "tmp");
416 
417   const llvm::Constant *Elts = LV.getExtVectorElts();
418 
419   // If the result of the expression is a non-vector type, we must be extracting
420   // a single element.  Just codegen as an extractelement.
421   const VectorType *ExprVT = ExprType->getAsVectorType();
422   if (!ExprVT) {
423     unsigned InIdx = getAccessedFieldNo(0, Elts);
424     llvm::Value *Elt = llvm::ConstantInt::get(
425                                       llvm::Type::getInt32Ty(VMContext), InIdx);
426     return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
427   }
428 
429   // Always use shuffle vector to try to retain the original program structure
430   unsigned NumResultElts = ExprVT->getNumElements();
431 
432   llvm::SmallVector<llvm::Constant*, 4> Mask;
433   for (unsigned i = 0; i != NumResultElts; ++i) {
434     unsigned InIdx = getAccessedFieldNo(i, Elts);
435     Mask.push_back(llvm::ConstantInt::get(
436                                      llvm::Type::getInt32Ty(VMContext), InIdx));
437   }
438 
439   llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
440   Vec = Builder.CreateShuffleVector(Vec,
441                                     llvm::UndefValue::get(Vec->getType()),
442                                     MaskV, "tmp");
443   return RValue::get(Vec);
444 }
445 
446 
447 
448 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
449 /// lvalue, where both are guaranteed to the have the same type, and that type
450 /// is 'Ty'.
451 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
452                                              QualType Ty) {
453   if (!Dst.isSimple()) {
454     if (Dst.isVectorElt()) {
455       // Read/modify/write the vector, inserting the new element.
456       llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(),
457                                             Dst.isVolatileQualified(), "tmp");
458       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
459                                         Dst.getVectorIdx(), "vecins");
460       Builder.CreateStore(Vec, Dst.getVectorAddr(),Dst.isVolatileQualified());
461       return;
462     }
463 
464     // If this is an update of extended vector elements, insert them as
465     // appropriate.
466     if (Dst.isExtVectorElt())
467       return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty);
468 
469     if (Dst.isBitfield())
470       return EmitStoreThroughBitfieldLValue(Src, Dst, Ty);
471 
472     if (Dst.isPropertyRef())
473       return EmitStoreThroughPropertyRefLValue(Src, Dst, Ty);
474 
475     if (Dst.isKVCRef())
476       return EmitStoreThroughKVCRefLValue(Src, Dst, Ty);
477 
478     assert(0 && "Unknown LValue type");
479   }
480 
481   if (Dst.isObjCWeak() && !Dst.isNonGC()) {
482     // load of a __weak object.
483     llvm::Value *LvalueDst = Dst.getAddress();
484     llvm::Value *src = Src.getScalarVal();
485      CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
486     return;
487   }
488 
489   if (Dst.isObjCStrong() && !Dst.isNonGC()) {
490     // load of a __strong object.
491     llvm::Value *LvalueDst = Dst.getAddress();
492     llvm::Value *src = Src.getScalarVal();
493 #if 0
494     // FIXME: We cannot positively determine if we have an 'ivar' assignment,
495     // object assignment or an unknown assignment. For now, generate call to
496     // objc_assign_strongCast assignment which is a safe, but consevative
497     // assumption.
498     if (Dst.isObjCIvar())
499       CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, LvalueDst);
500     else
501       CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst);
502 #endif
503     if (Dst.isGlobalObjCRef())
504       CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst);
505     else
506       CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
507     return;
508   }
509 
510   assert(Src.isScalar() && "Can't emit an agg store with this method");
511   EmitStoreOfScalar(Src.getScalarVal(), Dst.getAddress(),
512                     Dst.isVolatileQualified(), Ty);
513 }
514 
515 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
516                                                      QualType Ty,
517                                                      llvm::Value **Result) {
518   unsigned StartBit = Dst.getBitfieldStartBit();
519   unsigned BitfieldSize = Dst.getBitfieldSize();
520   llvm::Value *Ptr = Dst.getBitfieldAddr();
521 
522   const llvm::Type *EltTy =
523     cast<llvm::PointerType>(Ptr->getType())->getElementType();
524   unsigned EltTySize = CGM.getTargetData().getTypeSizeInBits(EltTy);
525 
526   // Get the new value, cast to the appropriate type and masked to exactly the
527   // size of the bit-field.
528   llvm::Value *SrcVal = Src.getScalarVal();
529   llvm::Value *NewVal = Builder.CreateIntCast(SrcVal, EltTy, false, "tmp");
530   llvm::Constant *Mask = llvm::ConstantInt::get(VMContext,
531                            llvm::APInt::getLowBitsSet(EltTySize, BitfieldSize));
532   NewVal = Builder.CreateAnd(NewVal, Mask, "bf.value");
533 
534   // Return the new value of the bit-field, if requested.
535   if (Result) {
536     // Cast back to the proper type for result.
537     const llvm::Type *SrcTy = SrcVal->getType();
538     llvm::Value *SrcTrunc = Builder.CreateIntCast(NewVal, SrcTy, false,
539                                                   "bf.reload.val");
540 
541     // Sign extend if necessary.
542     if (Dst.isBitfieldSigned()) {
543       unsigned SrcTySize = CGM.getTargetData().getTypeSizeInBits(SrcTy);
544       llvm::Value *ExtraBits = llvm::ConstantInt::get(SrcTy,
545                                                       SrcTySize - BitfieldSize);
546       SrcTrunc = Builder.CreateAShr(Builder.CreateShl(SrcTrunc, ExtraBits),
547                                     ExtraBits, "bf.reload.sext");
548     }
549 
550     *Result = SrcTrunc;
551   }
552 
553   // In some cases the bitfield may straddle two memory locations.  Emit the low
554   // part first and check to see if the high needs to be done.
555   unsigned LowBits = std::min(BitfieldSize, EltTySize - StartBit);
556   llvm::Value *LowVal = Builder.CreateLoad(Ptr, Dst.isVolatileQualified(),
557                                            "bf.prev.low");
558 
559   // Compute the mask for zero-ing the low part of this bitfield.
560   llvm::Constant *InvMask =
561     llvm::ConstantInt::get(VMContext,
562              ~llvm::APInt::getBitsSet(EltTySize, StartBit, StartBit + LowBits));
563 
564   // Compute the new low part as
565   //   LowVal = (LowVal & InvMask) | (NewVal << StartBit),
566   // with the shift of NewVal implicitly stripping the high bits.
567   llvm::Value *NewLowVal =
568     Builder.CreateShl(NewVal, llvm::ConstantInt::get(EltTy, StartBit),
569                       "bf.value.lo");
570   LowVal = Builder.CreateAnd(LowVal, InvMask, "bf.prev.lo.cleared");
571   LowVal = Builder.CreateOr(LowVal, NewLowVal, "bf.new.lo");
572 
573   // Write back.
574   Builder.CreateStore(LowVal, Ptr, Dst.isVolatileQualified());
575 
576   // If the low part doesn't cover the bitfield emit a high part.
577   if (LowBits < BitfieldSize) {
578     unsigned HighBits = BitfieldSize - LowBits;
579     llvm::Value *HighPtr =  Builder.CreateGEP(Ptr, llvm::ConstantInt::get(
580                             llvm::Type::getInt32Ty(VMContext), 1), "bf.ptr.hi");
581     llvm::Value *HighVal = Builder.CreateLoad(HighPtr,
582                                               Dst.isVolatileQualified(),
583                                               "bf.prev.hi");
584 
585     // Compute the mask for zero-ing the high part of this bitfield.
586     llvm::Constant *InvMask =
587       llvm::ConstantInt::get(VMContext, ~llvm::APInt::getLowBitsSet(EltTySize,
588                                HighBits));
589 
590     // Compute the new high part as
591     //   HighVal = (HighVal & InvMask) | (NewVal lshr LowBits),
592     // where the high bits of NewVal have already been cleared and the
593     // shift stripping the low bits.
594     llvm::Value *NewHighVal =
595       Builder.CreateLShr(NewVal, llvm::ConstantInt::get(EltTy, LowBits),
596                         "bf.value.high");
597     HighVal = Builder.CreateAnd(HighVal, InvMask, "bf.prev.hi.cleared");
598     HighVal = Builder.CreateOr(HighVal, NewHighVal, "bf.new.hi");
599 
600     // Write back.
601     Builder.CreateStore(HighVal, HighPtr, Dst.isVolatileQualified());
602   }
603 }
604 
605 void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
606                                                         LValue Dst,
607                                                         QualType Ty) {
608   EmitObjCPropertySet(Dst.getPropertyRefExpr(), Src);
609 }
610 
611 void CodeGenFunction::EmitStoreThroughKVCRefLValue(RValue Src,
612                                                    LValue Dst,
613                                                    QualType Ty) {
614   EmitObjCPropertySet(Dst.getKVCRefExpr(), Src);
615 }
616 
617 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
618                                                                LValue Dst,
619                                                                QualType Ty) {
620   // This access turns into a read/modify/write of the vector.  Load the input
621   // value now.
622   llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(),
623                                         Dst.isVolatileQualified(), "tmp");
624   const llvm::Constant *Elts = Dst.getExtVectorElts();
625 
626   llvm::Value *SrcVal = Src.getScalarVal();
627 
628   if (const VectorType *VTy = Ty->getAsVectorType()) {
629     unsigned NumSrcElts = VTy->getNumElements();
630     unsigned NumDstElts =
631        cast<llvm::VectorType>(Vec->getType())->getNumElements();
632     if (NumDstElts == NumSrcElts) {
633       // Use shuffle vector is the src and destination are the same number of
634       // elements and restore the vector mask since it is on the side it will be
635       // stored.
636       llvm::SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
637       for (unsigned i = 0; i != NumSrcElts; ++i) {
638         unsigned InIdx = getAccessedFieldNo(i, Elts);
639         Mask[InIdx] = llvm::ConstantInt::get(
640                                           llvm::Type::getInt32Ty(VMContext), i);
641       }
642 
643       llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
644       Vec = Builder.CreateShuffleVector(SrcVal,
645                                         llvm::UndefValue::get(Vec->getType()),
646                                         MaskV, "tmp");
647     } else if (NumDstElts > NumSrcElts) {
648       // Extended the source vector to the same length and then shuffle it
649       // into the destination.
650       // FIXME: since we're shuffling with undef, can we just use the indices
651       //        into that?  This could be simpler.
652       llvm::SmallVector<llvm::Constant*, 4> ExtMask;
653       unsigned i;
654       for (i = 0; i != NumSrcElts; ++i)
655         ExtMask.push_back(llvm::ConstantInt::get(
656                                          llvm::Type::getInt32Ty(VMContext), i));
657       for (; i != NumDstElts; ++i)
658         ExtMask.push_back(llvm::UndefValue::get(
659                                             llvm::Type::getInt32Ty(VMContext)));
660       llvm::Value *ExtMaskV = llvm::ConstantVector::get(&ExtMask[0],
661                                                         ExtMask.size());
662       llvm::Value *ExtSrcVal =
663         Builder.CreateShuffleVector(SrcVal,
664                                     llvm::UndefValue::get(SrcVal->getType()),
665                                     ExtMaskV, "tmp");
666       // build identity
667       llvm::SmallVector<llvm::Constant*, 4> Mask;
668       for (unsigned i = 0; i != NumDstElts; ++i) {
669         Mask.push_back(llvm::ConstantInt::get(
670                                         llvm::Type::getInt32Ty(VMContext), i));
671       }
672       // modify when what gets shuffled in
673       for (unsigned i = 0; i != NumSrcElts; ++i) {
674         unsigned Idx = getAccessedFieldNo(i, Elts);
675         Mask[Idx] = llvm::ConstantInt::get(
676                                llvm::Type::getInt32Ty(VMContext), i+NumDstElts);
677       }
678       llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
679       Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV, "tmp");
680     } else {
681       // We should never shorten the vector
682       assert(0 && "unexpected shorten vector length");
683     }
684   } else {
685     // If the Src is a scalar (not a vector) it must be updating one element.
686     unsigned InIdx = getAccessedFieldNo(0, Elts);
687     llvm::Value *Elt = llvm::ConstantInt::get(
688                                       llvm::Type::getInt32Ty(VMContext), InIdx);
689     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
690   }
691 
692   Builder.CreateStore(Vec, Dst.getExtVectorAddr(), Dst.isVolatileQualified());
693 }
694 
695 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
696   const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
697 
698   if (VD && (VD->isBlockVarDecl() || isa<ParmVarDecl>(VD) ||
699         isa<ImplicitParamDecl>(VD))) {
700     LValue LV;
701     bool NonGCable = VD->hasLocalStorage() &&
702       !VD->hasAttr<BlocksAttr>();
703     if (VD->hasExternalStorage()) {
704       llvm::Value *V = CGM.GetAddrOfGlobalVar(VD);
705       if (VD->getType()->isReferenceType())
706         V = Builder.CreateLoad(V, "tmp");
707       LV = LValue::MakeAddr(V, E->getType().getCVRQualifiers(),
708                             getContext().getObjCGCAttrKind(E->getType()),
709                             E->getType().getAddressSpace());
710     } else {
711       llvm::Value *V = LocalDeclMap[VD];
712       assert(V && "DeclRefExpr not entered in LocalDeclMap?");
713       // local variables do not get their gc attribute set.
714       QualType::GCAttrTypes attr = QualType::GCNone;
715       // local static?
716       if (!NonGCable)
717         attr = getContext().getObjCGCAttrKind(E->getType());
718       if (VD->hasAttr<BlocksAttr>()) {
719         V = Builder.CreateStructGEP(V, 1, "forwarding");
720         V = Builder.CreateLoad(V, false);
721         V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
722                                     VD->getNameAsString());
723       }
724       if (VD->getType()->isReferenceType())
725         V = Builder.CreateLoad(V, "tmp");
726       LV = LValue::MakeAddr(V, E->getType().getCVRQualifiers(), attr,
727                             E->getType().getAddressSpace());
728     }
729     LValue::SetObjCNonGC(LV, NonGCable);
730     return LV;
731   } else if (VD && VD->isFileVarDecl()) {
732     llvm::Value *V = CGM.GetAddrOfGlobalVar(VD);
733     if (VD->getType()->isReferenceType())
734       V = Builder.CreateLoad(V, "tmp");
735     LValue LV = LValue::MakeAddr(V, E->getType().getCVRQualifiers(),
736                                  getContext().getObjCGCAttrKind(E->getType()),
737                                  E->getType().getAddressSpace());
738     if (LV.isObjCStrong())
739       LV.SetGlobalObjCRef(LV, true);
740     return LV;
741   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
742     llvm::Value* V = CGM.GetAddrOfFunction(FD);
743     if (!FD->hasPrototype()) {
744       if (const FunctionProtoType *Proto =
745               FD->getType()->getAsFunctionProtoType()) {
746         // Ugly case: for a K&R-style definition, the type of the definition
747         // isn't the same as the type of a use.  Correct for this with a
748         // bitcast.
749         QualType NoProtoType =
750             getContext().getFunctionNoProtoType(Proto->getResultType());
751         NoProtoType = getContext().getPointerType(NoProtoType);
752         V = Builder.CreateBitCast(V, ConvertType(NoProtoType), "tmp");
753       }
754     }
755     return LValue::MakeAddr(V, E->getType().getCVRQualifiers(),
756                             getContext().getObjCGCAttrKind(E->getType()),
757                             E->getType().getAddressSpace());
758   } else if (const ImplicitParamDecl *IPD =
759       dyn_cast<ImplicitParamDecl>(E->getDecl())) {
760     llvm::Value *V = LocalDeclMap[IPD];
761     assert(V && "BlockVarDecl not entered in LocalDeclMap?");
762     return LValue::MakeAddr(V, E->getType().getCVRQualifiers(),
763                             getContext().getObjCGCAttrKind(E->getType()),
764                             E->getType().getAddressSpace());
765   }
766   assert(0 && "Unimp declref");
767   //an invalid LValue, but the assert will
768   //ensure that this point is never reached.
769   return LValue();
770 }
771 
772 LValue CodeGenFunction::EmitBlockDeclRefLValue(const BlockDeclRefExpr *E) {
773   return LValue::MakeAddr(GetAddrOfBlockDecl(E),
774                           E->getType().getCVRQualifiers(),
775                           getContext().getObjCGCAttrKind(E->getType()),
776                           E->getType().getAddressSpace());
777 }
778 
779 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
780   // __extension__ doesn't affect lvalue-ness.
781   if (E->getOpcode() == UnaryOperator::Extension)
782     return EmitLValue(E->getSubExpr());
783 
784   QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
785   switch (E->getOpcode()) {
786   default: assert(0 && "Unknown unary operator lvalue!");
787   case UnaryOperator::Deref:
788     {
789       QualType T = E->getSubExpr()->getType()->getPointeeType();
790       assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
791 
792       LValue LV = LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()),
793                                    T.getCVRQualifiers(),
794                                    getContext().getObjCGCAttrKind(T),
795                                    ExprTy.getAddressSpace());
796      // We should not generate __weak write barrier on indirect reference
797      // of a pointer to object; as in void foo (__weak id *param); *param = 0;
798      // But, we continue to generate __strong write barrier on indirect write
799      // into a pointer to object.
800      if (getContext().getLangOptions().ObjC1 &&
801          getContext().getLangOptions().getGCMode() != LangOptions::NonGC &&
802          LV.isObjCWeak())
803        LValue::SetObjCNonGC(LV, !E->isOBJCGCCandidate(getContext()));
804      return LV;
805     }
806   case UnaryOperator::Real:
807   case UnaryOperator::Imag:
808     LValue LV = EmitLValue(E->getSubExpr());
809     unsigned Idx = E->getOpcode() == UnaryOperator::Imag;
810     return LValue::MakeAddr(Builder.CreateStructGEP(LV.getAddress(),
811                                                     Idx, "idx"),
812                             ExprTy.getCVRQualifiers(),
813                             QualType::GCNone,
814                             ExprTy.getAddressSpace());
815   }
816 }
817 
818 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
819   return LValue::MakeAddr(CGM.GetAddrOfConstantStringFromLiteral(E), 0);
820 }
821 
822 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
823   return LValue::MakeAddr(CGM.GetAddrOfConstantStringFromObjCEncode(E), 0);
824 }
825 
826 
827 LValue CodeGenFunction::EmitPredefinedFunctionName(unsigned Type) {
828   std::string GlobalVarName;
829 
830   switch (Type) {
831   default:
832     assert(0 && "Invalid type");
833   case PredefinedExpr::Func:
834     GlobalVarName = "__func__.";
835     break;
836   case PredefinedExpr::Function:
837     GlobalVarName = "__FUNCTION__.";
838     break;
839   case PredefinedExpr::PrettyFunction:
840     GlobalVarName = "__PRETTY_FUNCTION__.";
841     break;
842   }
843 
844   llvm::StringRef FnName = CurFn->getName();
845   if (FnName.startswith("\01"))
846     FnName = FnName.substr(1);
847   GlobalVarName += FnName;
848 
849   std::string FunctionName =
850     PredefinedExpr::ComputeName(getContext(), (PredefinedExpr::IdentType)Type,
851                                 CurCodeDecl);
852 
853   llvm::Constant *C =
854     CGM.GetAddrOfConstantCString(FunctionName, GlobalVarName.c_str());
855   return LValue::MakeAddr(C, 0);
856 }
857 
858 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
859   switch (E->getIdentType()) {
860   default:
861     return EmitUnsupportedLValue(E, "predefined expression");
862   case PredefinedExpr::Func:
863   case PredefinedExpr::Function:
864   case PredefinedExpr::PrettyFunction:
865     return EmitPredefinedFunctionName(E->getIdentType());
866   }
867 }
868 
869 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
870   // The index must always be an integer, which is not an aggregate.  Emit it.
871   llvm::Value *Idx = EmitScalarExpr(E->getIdx());
872   QualType IdxTy  = E->getIdx()->getType();
873   bool IdxSigned = IdxTy->isSignedIntegerType();
874 
875   // If the base is a vector type, then we are forming a vector element lvalue
876   // with this subscript.
877   if (E->getBase()->getType()->isVectorType()) {
878     // Emit the vector as an lvalue to get its address.
879     LValue LHS = EmitLValue(E->getBase());
880     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
881     Idx = Builder.CreateIntCast(Idx,
882                           llvm::Type::getInt32Ty(VMContext), IdxSigned, "vidx");
883     return LValue::MakeVectorElt(LHS.getAddress(), Idx,
884       E->getBase()->getType().getCVRQualifiers());
885   }
886 
887   // The base must be a pointer, which is not an aggregate.  Emit it.
888   llvm::Value *Base = EmitScalarExpr(E->getBase());
889 
890   // Extend or truncate the index type to 32 or 64-bits.
891   unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
892   if (IdxBitwidth != LLVMPointerWidth)
893     Idx = Builder.CreateIntCast(Idx,
894                             llvm::IntegerType::get(VMContext, LLVMPointerWidth),
895                                 IdxSigned, "idxprom");
896 
897   // We know that the pointer points to a type of the correct size, unless the
898   // size is a VLA or Objective-C interface.
899   llvm::Value *Address = 0;
900   if (const VariableArrayType *VAT =
901         getContext().getAsVariableArrayType(E->getType())) {
902     llvm::Value *VLASize = GetVLASize(VAT);
903 
904     Idx = Builder.CreateMul(Idx, VLASize);
905 
906     QualType BaseType = getContext().getBaseElementType(VAT);
907 
908     uint64_t BaseTypeSize = getContext().getTypeSize(BaseType) / 8;
909     Idx = Builder.CreateUDiv(Idx,
910                              llvm::ConstantInt::get(Idx->getType(),
911                                                     BaseTypeSize));
912     Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
913   } else if (const ObjCInterfaceType *OIT =
914              dyn_cast<ObjCInterfaceType>(E->getType())) {
915     llvm::Value *InterfaceSize =
916       llvm::ConstantInt::get(Idx->getType(),
917                              getContext().getTypeSize(OIT) / 8);
918 
919     Idx = Builder.CreateMul(Idx, InterfaceSize);
920 
921     llvm::Type *i8PTy =
922             llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
923     Address = Builder.CreateGEP(Builder.CreateBitCast(Base, i8PTy),
924                                 Idx, "arrayidx");
925     Address = Builder.CreateBitCast(Address, Base->getType());
926   } else {
927     Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
928   }
929 
930   QualType T = E->getBase()->getType()->getPointeeType();
931   assert(!T.isNull() &&
932          "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
933 
934   LValue LV = LValue::MakeAddr(Address,
935                                T.getCVRQualifiers(),
936                                getContext().getObjCGCAttrKind(T),
937                                E->getBase()->getType().getAddressSpace());
938   if (getContext().getLangOptions().ObjC1 &&
939       getContext().getLangOptions().getGCMode() != LangOptions::NonGC)
940     LValue::SetObjCNonGC(LV, !E->isOBJCGCCandidate(getContext()));
941   return LV;
942 }
943 
944 static
945 llvm::Constant *GenerateConstantVector(llvm::LLVMContext &VMContext,
946                                        llvm::SmallVector<unsigned, 4> &Elts) {
947   llvm::SmallVector<llvm::Constant *, 4> CElts;
948 
949   for (unsigned i = 0, e = Elts.size(); i != e; ++i)
950     CElts.push_back(llvm::ConstantInt::get(
951                                    llvm::Type::getInt32Ty(VMContext), Elts[i]));
952 
953   return llvm::ConstantVector::get(&CElts[0], CElts.size());
954 }
955 
956 LValue CodeGenFunction::
957 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
958   // Emit the base vector as an l-value.
959   LValue Base;
960 
961   // ExtVectorElementExpr's base can either be a vector or pointer to vector.
962   if (!E->isArrow()) {
963     assert(E->getBase()->getType()->isVectorType());
964     Base = EmitLValue(E->getBase());
965   } else {
966     const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
967     llvm::Value *Ptr = EmitScalarExpr(E->getBase());
968     Base = LValue::MakeAddr(Ptr, PT->getPointeeType().getCVRQualifiers(),
969                             QualType::GCNone,
970                             PT->getPointeeType().getAddressSpace());
971   }
972 
973   // Encode the element access list into a vector of unsigned indices.
974   llvm::SmallVector<unsigned, 4> Indices;
975   E->getEncodedElementAccess(Indices);
976 
977   if (Base.isSimple()) {
978     llvm::Constant *CV = GenerateConstantVector(VMContext, Indices);
979     return LValue::MakeExtVectorElt(Base.getAddress(), CV,
980                                     Base.getQualifiers());
981   }
982   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
983 
984   llvm::Constant *BaseElts = Base.getExtVectorElts();
985   llvm::SmallVector<llvm::Constant *, 4> CElts;
986 
987   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
988     if (isa<llvm::ConstantAggregateZero>(BaseElts))
989       CElts.push_back(llvm::ConstantInt::get(
990                                          llvm::Type::getInt32Ty(VMContext), 0));
991     else
992       CElts.push_back(BaseElts->getOperand(Indices[i]));
993   }
994   llvm::Constant *CV = llvm::ConstantVector::get(&CElts[0], CElts.size());
995   return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV,
996                                   Base.getQualifiers());
997 }
998 
999 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
1000   bool isUnion = false;
1001   bool isIvar = false;
1002   bool isNonGC = false;
1003   Expr *BaseExpr = E->getBase();
1004   llvm::Value *BaseValue = NULL;
1005   unsigned CVRQualifiers=0;
1006 
1007   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
1008   if (E->isArrow()) {
1009     BaseValue = EmitScalarExpr(BaseExpr);
1010     const PointerType *PTy =
1011       BaseExpr->getType()->getAs<PointerType>();
1012     if (PTy->getPointeeType()->isUnionType())
1013       isUnion = true;
1014     CVRQualifiers = PTy->getPointeeType().getCVRQualifiers();
1015   } else if (isa<ObjCPropertyRefExpr>(BaseExpr->IgnoreParens()) ||
1016              isa<ObjCImplicitSetterGetterRefExpr>(
1017                BaseExpr->IgnoreParens())) {
1018     RValue RV = EmitObjCPropertyGet(BaseExpr);
1019     BaseValue = RV.getAggregateAddr();
1020     if (BaseExpr->getType()->isUnionType())
1021       isUnion = true;
1022     CVRQualifiers = BaseExpr->getType().getCVRQualifiers();
1023   } else {
1024     LValue BaseLV = EmitLValue(BaseExpr);
1025     if (BaseLV.isObjCIvar())
1026       isIvar = true;
1027     if (BaseLV.isNonGC())
1028       isNonGC = true;
1029     // FIXME: this isn't right for bitfields.
1030     BaseValue = BaseLV.getAddress();
1031     QualType BaseTy = BaseExpr->getType();
1032     if (BaseTy->isUnionType())
1033       isUnion = true;
1034     CVRQualifiers = BaseTy.getCVRQualifiers();
1035   }
1036 
1037   FieldDecl *Field = dyn_cast<FieldDecl>(E->getMemberDecl());
1038   // FIXME: Handle non-field member expressions
1039   assert(Field && "No code generation for non-field member references");
1040   LValue MemExpLV = EmitLValueForField(BaseValue, Field, isUnion,
1041                                        CVRQualifiers);
1042   LValue::SetObjCIvar(MemExpLV, isIvar);
1043   LValue::SetObjCNonGC(MemExpLV, isNonGC);
1044   return MemExpLV;
1045 }
1046 
1047 LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value* BaseValue,
1048                                               FieldDecl* Field,
1049                                               unsigned CVRQualifiers) {
1050   CodeGenTypes::BitFieldInfo Info = CGM.getTypes().getBitFieldInfo(Field);
1051 
1052   // FIXME: CodeGenTypes should expose a method to get the appropriate type for
1053   // FieldTy (the appropriate type is ABI-dependent).
1054   const llvm::Type *FieldTy =
1055     CGM.getTypes().ConvertTypeForMem(Field->getType());
1056   const llvm::PointerType *BaseTy =
1057   cast<llvm::PointerType>(BaseValue->getType());
1058   unsigned AS = BaseTy->getAddressSpace();
1059   BaseValue = Builder.CreateBitCast(BaseValue,
1060                                     llvm::PointerType::get(FieldTy, AS),
1061                                     "tmp");
1062 
1063   llvm::Value *Idx =
1064     llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), Info.FieldNo);
1065   llvm::Value *V = Builder.CreateGEP(BaseValue, Idx, "tmp");
1066 
1067   return LValue::MakeBitfield(V, Info.Start, Info.Size,
1068                               Field->getType()->isSignedIntegerType(),
1069                             Field->getType().getCVRQualifiers()|CVRQualifiers);
1070 }
1071 
1072 LValue CodeGenFunction::EmitLValueForField(llvm::Value* BaseValue,
1073                                            FieldDecl* Field,
1074                                            bool isUnion,
1075                                            unsigned CVRQualifiers) {
1076   if (Field->isBitField())
1077     return EmitLValueForBitfield(BaseValue, Field, CVRQualifiers);
1078 
1079   unsigned idx = CGM.getTypes().getLLVMFieldNo(Field);
1080   llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp");
1081 
1082   // Match union field type.
1083   if (isUnion) {
1084     const llvm::Type *FieldTy =
1085       CGM.getTypes().ConvertTypeForMem(Field->getType());
1086     const llvm::PointerType * BaseTy =
1087       cast<llvm::PointerType>(BaseValue->getType());
1088     unsigned AS = BaseTy->getAddressSpace();
1089     V = Builder.CreateBitCast(V,
1090                               llvm::PointerType::get(FieldTy, AS),
1091                               "tmp");
1092   }
1093   if (Field->getType()->isReferenceType())
1094     V = Builder.CreateLoad(V, "tmp");
1095 
1096   QualType::GCAttrTypes attr = QualType::GCNone;
1097   if (CGM.getLangOptions().ObjC1 &&
1098       CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
1099     QualType Ty = Field->getType();
1100     attr = Ty.getObjCGCAttr();
1101     if (attr != QualType::GCNone) {
1102       // __weak attribute on a field is ignored.
1103       if (attr == QualType::Weak)
1104         attr = QualType::GCNone;
1105     } else if (Ty->isObjCObjectPointerType())
1106       attr = QualType::Strong;
1107   }
1108   LValue LV =
1109     LValue::MakeAddr(V,
1110                      Field->getType().getCVRQualifiers()|CVRQualifiers,
1111                      attr,
1112                      Field->getType().getAddressSpace());
1113   return LV;
1114 }
1115 
1116 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr* E){
1117   const llvm::Type *LTy = ConvertType(E->getType());
1118   llvm::Value *DeclPtr = CreateTempAlloca(LTy, ".compoundliteral");
1119 
1120   const Expr* InitExpr = E->getInitializer();
1121   LValue Result = LValue::MakeAddr(DeclPtr, E->getType().getCVRQualifiers(),
1122                                    QualType::GCNone,
1123                                    E->getType().getAddressSpace());
1124 
1125   if (E->getType()->isComplexType()) {
1126     EmitComplexExprIntoAddr(InitExpr, DeclPtr, false);
1127   } else if (hasAggregateLLVMType(E->getType())) {
1128     EmitAnyExpr(InitExpr, DeclPtr, false);
1129   } else {
1130     EmitStoreThroughLValue(EmitAnyExpr(InitExpr), Result, E->getType());
1131   }
1132 
1133   return Result;
1134 }
1135 
1136 LValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator* E) {
1137   if (E->isLvalue(getContext()) == Expr::LV_Valid)
1138     return EmitUnsupportedLValue(E, "conditional operator");
1139 
1140   // ?: here should be an aggregate.
1141   assert((hasAggregateLLVMType(E->getType()) &&
1142           !E->getType()->isAnyComplexType()) &&
1143          "Unexpected conditional operator!");
1144 
1145   llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType()));
1146   EmitAggExpr(E, Temp, false);
1147 
1148   return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(),
1149                           getContext().getObjCGCAttrKind(E->getType()),
1150                           E->getType().getAddressSpace());
1151 
1152 }
1153 
1154 /// EmitCastLValue - Casts are never lvalues.  If a cast is needed by the code
1155 /// generator in an lvalue context, then it must mean that we need the address
1156 /// of an aggregate in order to access one of its fields.  This can happen for
1157 /// all the reasons that casts are permitted with aggregate result, including
1158 /// noop aggregate casts, and cast from scalar to union.
1159 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
1160   switch (E->getCastKind()) {
1161   default:
1162     // If this is an lvalue cast, treat it as a no-op.
1163     // FIXME: We shouldn't need to check for this explicitly!
1164     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
1165       if (ICE->isLvalueCast())
1166         return EmitLValue(E->getSubExpr());
1167 
1168     assert(0 && "Unhandled cast!");
1169 
1170   case CastExpr::CK_NoOp:
1171   case CastExpr::CK_ConstructorConversion:
1172   case CastExpr::CK_UserDefinedConversion:
1173     return EmitLValue(E->getSubExpr());
1174 
1175   case CastExpr::CK_DerivedToBase: {
1176     const RecordType *DerivedClassTy =
1177       E->getSubExpr()->getType()->getAs<RecordType>();
1178     CXXRecordDecl *DerivedClassDecl =
1179       cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1180 
1181     const RecordType *BaseClassTy = E->getType()->getAs<RecordType>();
1182     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseClassTy->getDecl());
1183 
1184     LValue LV = EmitLValue(E->getSubExpr());
1185 
1186     // Perform the derived-to-base conversion
1187     llvm::Value *Base =
1188       GetAddressCXXOfBaseClass(LV.getAddress(), DerivedClassDecl,
1189                                BaseClassDecl, /*NullCheckValue=*/false);
1190 
1191     return LValue::MakeAddr(Base, E->getType().getCVRQualifiers(),
1192                             getContext().getObjCGCAttrKind(E->getType()),
1193                             E->getType().getAddressSpace());
1194   }
1195 
1196   case CastExpr::CK_ToUnion: {
1197     llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType()));
1198     EmitAnyExpr(E->getSubExpr(), Temp, false);
1199 
1200     return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(),
1201                             getContext().getObjCGCAttrKind(E->getType()),
1202                             E->getType().getAddressSpace());
1203     }
1204   }
1205 }
1206 
1207 //===--------------------------------------------------------------------===//
1208 //                             Expression Emission
1209 //===--------------------------------------------------------------------===//
1210 
1211 
1212 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
1213   // Builtins never have block type.
1214   if (E->getCallee()->getType()->isBlockPointerType())
1215     return EmitBlockCallExpr(E);
1216 
1217   if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E))
1218     return EmitCXXMemberCallExpr(CE);
1219 
1220   const Decl *TargetDecl = 0;
1221   if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E->getCallee())) {
1222     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1223       TargetDecl = DRE->getDecl();
1224       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(TargetDecl))
1225         if (unsigned builtinID = FD->getBuiltinID())
1226           return EmitBuiltinExpr(FD, builtinID, E);
1227     }
1228   }
1229 
1230   if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E))
1231     if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
1232       return EmitCXXOperatorMemberCallExpr(CE, MD);
1233 
1234   if (isa<CXXPseudoDestructorExpr>(E->getCallee())) {
1235     // C++ [expr.pseudo]p1:
1236     //   The result shall only be used as the operand for the function call
1237     //   operator (), and the result of such a call has type void. The only
1238     //   effect is the evaluation of the postfix-expression before the dot or
1239     //   arrow.
1240     EmitScalarExpr(E->getCallee());
1241     return RValue::get(0);
1242   }
1243 
1244   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
1245   return EmitCall(Callee, E->getCallee()->getType(),
1246                   E->arg_begin(), E->arg_end(), TargetDecl);
1247 }
1248 
1249 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
1250   // Comma expressions just emit their LHS then their RHS as an l-value.
1251   if (E->getOpcode() == BinaryOperator::Comma) {
1252     EmitAnyExpr(E->getLHS());
1253     return EmitLValue(E->getRHS());
1254   }
1255 
1256   // Can only get l-value for binary operator expressions which are a
1257   // simple assignment of aggregate type.
1258   if (E->getOpcode() != BinaryOperator::Assign)
1259     return EmitUnsupportedLValue(E, "binary l-value expression");
1260 
1261   llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType()));
1262   EmitAggExpr(E, Temp, false);
1263   // FIXME: Are these qualifiers correct?
1264   return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(),
1265                           getContext().getObjCGCAttrKind(E->getType()),
1266                           E->getType().getAddressSpace());
1267 }
1268 
1269 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
1270   RValue RV = EmitCallExpr(E);
1271 
1272   if (RV.isScalar()) {
1273     assert(E->getCallReturnType()->isReferenceType() &&
1274            "Can't have a scalar return unless the return type is a "
1275            "reference type!");
1276 
1277     return LValue::MakeAddr(RV.getScalarVal(), E->getType().getCVRQualifiers(),
1278                             getContext().getObjCGCAttrKind(E->getType()),
1279                             E->getType().getAddressSpace());
1280   }
1281 
1282   return LValue::MakeAddr(RV.getAggregateAddr(),
1283                           E->getType().getCVRQualifiers(),
1284                           getContext().getObjCGCAttrKind(E->getType()),
1285                           E->getType().getAddressSpace());
1286 }
1287 
1288 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
1289   // FIXME: This shouldn't require another copy.
1290   llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType()));
1291   EmitAggExpr(E, Temp, false);
1292   return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(),
1293                           QualType::GCNone, E->getType().getAddressSpace());
1294 }
1295 
1296 LValue
1297 CodeGenFunction::EmitCXXConditionDeclLValue(const CXXConditionDeclExpr *E) {
1298   EmitLocalBlockVarDecl(*E->getVarDecl());
1299   return EmitDeclRefLValue(E);
1300 }
1301 
1302 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
1303   llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(E->getType()), "tmp");
1304   EmitCXXConstructExpr(Temp, E);
1305   return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers(),
1306                           QualType::GCNone, E->getType().getAddressSpace());
1307 }
1308 
1309 LValue
1310 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
1311   LValue LV = EmitLValue(E->getSubExpr());
1312 
1313   PushCXXTemporary(E->getTemporary(), LV.getAddress());
1314 
1315   return LV;
1316 }
1317 
1318 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
1319   // Can only get l-value for message expression returning aggregate type
1320   RValue RV = EmitObjCMessageExpr(E);
1321   // FIXME: can this be volatile?
1322   return LValue::MakeAddr(RV.getAggregateAddr(),
1323                           E->getType().getCVRQualifiers(),
1324                           getContext().getObjCGCAttrKind(E->getType()),
1325                           E->getType().getAddressSpace());
1326 }
1327 
1328 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
1329                                              const ObjCIvarDecl *Ivar) {
1330   return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
1331 }
1332 
1333 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
1334                                           llvm::Value *BaseValue,
1335                                           const ObjCIvarDecl *Ivar,
1336                                           unsigned CVRQualifiers) {
1337   return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
1338                                                    Ivar, CVRQualifiers);
1339 }
1340 
1341 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
1342   // FIXME: A lot of the code below could be shared with EmitMemberExpr.
1343   llvm::Value *BaseValue = 0;
1344   const Expr *BaseExpr = E->getBase();
1345   unsigned CVRQualifiers = 0;
1346   QualType ObjectTy;
1347   if (E->isArrow()) {
1348     BaseValue = EmitScalarExpr(BaseExpr);
1349     ObjectTy = BaseExpr->getType()->getPointeeType();
1350     CVRQualifiers = ObjectTy.getCVRQualifiers();
1351   } else {
1352     LValue BaseLV = EmitLValue(BaseExpr);
1353     // FIXME: this isn't right for bitfields.
1354     BaseValue = BaseLV.getAddress();
1355     ObjectTy = BaseExpr->getType();
1356     CVRQualifiers = ObjectTy.getCVRQualifiers();
1357   }
1358 
1359   return EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(), CVRQualifiers);
1360 }
1361 
1362 LValue
1363 CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
1364   // This is a special l-value that just issues sends when we load or store
1365   // through it.
1366   return LValue::MakePropertyRef(E, E->getType().getCVRQualifiers());
1367 }
1368 
1369 LValue
1370 CodeGenFunction::EmitObjCKVCRefLValue(
1371                                 const ObjCImplicitSetterGetterRefExpr *E) {
1372   // This is a special l-value that just issues sends when we load or store
1373   // through it.
1374   return LValue::MakeKVCRef(E, E->getType().getCVRQualifiers());
1375 }
1376 
1377 LValue
1378 CodeGenFunction::EmitObjCSuperExprLValue(const ObjCSuperExpr *E) {
1379   return EmitUnsupportedLValue(E, "use of super");
1380 }
1381 
1382 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
1383 
1384   // Can only get l-value for message expression returning aggregate type
1385   RValue RV = EmitAnyExprToTemp(E);
1386   // FIXME: can this be volatile?
1387   return LValue::MakeAddr(RV.getAggregateAddr(),
1388                           E->getType().getCVRQualifiers(),
1389                           getContext().getObjCGCAttrKind(E->getType()),
1390                           E->getType().getAddressSpace());
1391 }
1392 
1393 
1394 RValue CodeGenFunction::EmitCall(llvm::Value *Callee, QualType CalleeType,
1395                                  CallExpr::const_arg_iterator ArgBeg,
1396                                  CallExpr::const_arg_iterator ArgEnd,
1397                                  const Decl *TargetDecl) {
1398   // Get the actual function type. The callee type will always be a pointer to
1399   // function type or a block pointer type.
1400   assert(CalleeType->isFunctionPointerType() &&
1401          "Call must have function pointer type!");
1402 
1403   QualType FnType = CalleeType->getAs<PointerType>()->getPointeeType();
1404   QualType ResultType = FnType->getAsFunctionType()->getResultType();
1405 
1406   CallArgList Args;
1407   EmitCallArgs(Args, FnType->getAsFunctionProtoType(), ArgBeg, ArgEnd);
1408 
1409   // FIXME: We should not need to do this, it should be part of the function
1410   // type.
1411   unsigned CallingConvention = 0;
1412   if (const llvm::Function *F =
1413       dyn_cast<llvm::Function>(Callee->stripPointerCasts()))
1414     CallingConvention = F->getCallingConv();
1415   return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
1416                                                  CallingConvention),
1417                   Callee, Args, TargetDecl);
1418 }
1419