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   return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
33 }
34 
35 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
36 /// expression and compare the result against zero, returning an Int1Ty value.
37 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
38   QualType BoolTy = getContext().BoolTy;
39   if (!E->getType()->isAnyComplexType())
40     return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
41 
42   return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
43 }
44 
45 /// EmitAnyExpr - Emit code to compute the specified expression which can have
46 /// any type.  The result is returned as an RValue struct.  If this is an
47 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
48 /// the result should be returned.
49 RValue CodeGenFunction::EmitAnyExpr(const Expr *E, llvm::Value *AggLoc,
50                                     bool isAggLocVolatile) {
51   if (!hasAggregateLLVMType(E->getType()))
52     return RValue::get(EmitScalarExpr(E));
53   else if (E->getType()->isAnyComplexType())
54     return RValue::getComplex(EmitComplexExpr(E));
55 
56   EmitAggExpr(E, AggLoc, isAggLocVolatile);
57   return RValue::getAggregate(AggLoc);
58 }
59 
60 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result
61 /// will always be accessible even if no aggregate location is
62 /// provided.
63 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E, llvm::Value *AggLoc,
64                                           bool isAggLocVolatile) {
65   if (!AggLoc && hasAggregateLLVMType(E->getType()) &&
66       !E->getType()->isAnyComplexType())
67     AggLoc = CreateTempAlloca(ConvertType(E->getType()), "agg.tmp");
68   return EmitAnyExpr(E, AggLoc, isAggLocVolatile);
69 }
70 
71 /// getAccessedFieldNo - Given an encoded value and a result number, return
72 /// the input field number being accessed.
73 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
74                                              const llvm::Constant *Elts) {
75   if (isa<llvm::ConstantAggregateZero>(Elts))
76     return 0;
77 
78   return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue();
79 }
80 
81 
82 //===----------------------------------------------------------------------===//
83 //                         LValue Expression Emission
84 //===----------------------------------------------------------------------===//
85 
86 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
87                                               const char *Name) {
88   ErrorUnsupported(E, Name);
89   if (const ComplexType *CTy = E->getType()->getAsComplexType()) {
90     const llvm::Type *EltTy = ConvertType(CTy->getElementType());
91     llvm::Value *U = llvm::UndefValue::get(EltTy);
92     return RValue::getComplex(std::make_pair(U, U));
93   } else if (hasAggregateLLVMType(E->getType())) {
94     const llvm::Type *Ty =
95       llvm::PointerType::getUnqual(ConvertType(E->getType()));
96     return RValue::getAggregate(llvm::UndefValue::get(Ty));
97   } else {
98     const llvm::Type *Ty = ConvertType(E->getType());
99     return RValue::get(llvm::UndefValue::get(Ty));
100   }
101 }
102 
103 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
104                                               const char *Name) {
105   ErrorUnsupported(E, Name);
106   llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
107   return LValue::MakeAddr(llvm::UndefValue::get(Ty),
108                           E->getType().getCVRQualifiers());
109 }
110 
111 /// EmitLValue - Emit code to compute a designator that specifies the location
112 /// of the expression.
113 ///
114 /// This can return one of two things: a simple address or a bitfield
115 /// reference.  In either case, the LLVM Value* in the LValue structure is
116 /// guaranteed to be an LLVM pointer type.
117 ///
118 /// If this returns a bitfield reference, nothing about the pointee type of
119 /// the LLVM value is known: For example, it may not be a pointer to an
120 /// integer.
121 ///
122 /// If this returns a normal address, and if the lvalue's C type is fixed
123 /// size, this method guarantees that the returned pointer type will point to
124 /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
125 /// variable length type, this is not possible.
126 ///
127 LValue CodeGenFunction::EmitLValue(const Expr *E) {
128   switch (E->getStmtClass()) {
129   default: return EmitUnsupportedLValue(E, "l-value expression");
130 
131   case Expr::BinaryOperatorClass:
132     return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
133   case Expr::CallExprClass:
134   case Expr::CXXOperatorCallExprClass:
135     return EmitCallExprLValue(cast<CallExpr>(E));
136   case Expr::DeclRefExprClass:
137   case Expr::QualifiedDeclRefExprClass:
138     return EmitDeclRefLValue(cast<DeclRefExpr>(E));
139   case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
140   case Expr::PredefinedExprClass:
141     return EmitPredefinedLValue(cast<PredefinedExpr>(E));
142   case Expr::StringLiteralClass:
143     return EmitStringLiteralLValue(cast<StringLiteral>(E));
144 
145   case Expr::CXXConditionDeclExprClass:
146     return EmitCXXConditionDeclLValue(cast<CXXConditionDeclExpr>(E));
147 
148   case Expr::ObjCMessageExprClass:
149     return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
150   case Expr::ObjCIvarRefExprClass:
151     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
152   case Expr::ObjCPropertyRefExprClass:
153     return EmitObjCPropertyRefLValue(cast<ObjCPropertyRefExpr>(E));
154   case Expr::ObjCKVCRefExprClass:
155     return EmitObjCKVCRefLValue(cast<ObjCKVCRefExpr>(E));
156   case Expr::ObjCSuperExprClass:
157     return EmitObjCSuperExpr(cast<ObjCSuperExpr>(E));
158 
159   case Expr::UnaryOperatorClass:
160     return EmitUnaryOpLValue(cast<UnaryOperator>(E));
161   case Expr::ArraySubscriptExprClass:
162     return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
163   case Expr::ExtVectorElementExprClass:
164     return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
165   case Expr::MemberExprClass: return EmitMemberExpr(cast<MemberExpr>(E));
166   case Expr::CompoundLiteralExprClass:
167     return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
168   case Expr::ChooseExprClass:
169     // __builtin_choose_expr is the lvalue of the selected operand.
170     if (cast<ChooseExpr>(E)->isConditionTrue(getContext()))
171       return EmitLValue(cast<ChooseExpr>(E)->getLHS());
172     else
173       return EmitLValue(cast<ChooseExpr>(E)->getRHS());
174   }
175 }
176 
177 /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
178 /// this method emits the address of the lvalue, then loads the result as an
179 /// rvalue, returning the rvalue.
180 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
181   if (LV.isObjCWeak()) {
182     // load of a __weak object.
183     llvm::Value *AddrWeakObj = LV.getAddress();
184     llvm::Value *read_weak = CGM.getObjCRuntime().EmitObjCWeakRead(*this,
185                                                                    AddrWeakObj);
186     return RValue::get(read_weak);
187   }
188 
189   if (LV.isSimple()) {
190     llvm::Value *Ptr = LV.getAddress();
191     const llvm::Type *EltTy =
192       cast<llvm::PointerType>(Ptr->getType())->getElementType();
193 
194     // Simple scalar l-value.
195     if (EltTy->isSingleValueType()) {
196       llvm::Value *V = Builder.CreateLoad(Ptr, LV.isVolatileQualified(),"tmp");
197 
198       // Bool can have different representation in memory than in registers.
199       if (ExprType->isBooleanType()) {
200         if (V->getType() != llvm::Type::Int1Ty)
201           V = Builder.CreateTrunc(V, llvm::Type::Int1Ty, "tobool");
202       }
203 
204       return RValue::get(V);
205     }
206 
207     assert(ExprType->isFunctionType() && "Unknown scalar value");
208     return RValue::get(Ptr);
209   }
210 
211   if (LV.isVectorElt()) {
212     llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(),
213                                           LV.isVolatileQualified(), "tmp");
214     return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
215                                                     "vecext"));
216   }
217 
218   // If this is a reference to a subset of the elements of a vector, either
219   // shuffle the input or extract/insert them as appropriate.
220   if (LV.isExtVectorElt())
221     return EmitLoadOfExtVectorElementLValue(LV, ExprType);
222 
223   if (LV.isBitfield())
224     return EmitLoadOfBitfieldLValue(LV, ExprType);
225 
226   if (LV.isPropertyRef())
227     return EmitLoadOfPropertyRefLValue(LV, ExprType);
228 
229   if (LV.isKVCRef())
230     return EmitLoadOfKVCRefLValue(LV, ExprType);
231 
232   assert(0 && "Unknown LValue type!");
233   //an invalid RValue, but the assert will
234   //ensure that this point is never reached
235   return RValue();
236 }
237 
238 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
239                                                  QualType ExprType) {
240   unsigned StartBit = LV.getBitfieldStartBit();
241   unsigned BitfieldSize = LV.getBitfieldSize();
242   llvm::Value *Ptr = LV.getBitfieldAddr();
243 
244   const llvm::Type *EltTy =
245     cast<llvm::PointerType>(Ptr->getType())->getElementType();
246   unsigned EltTySize = CGM.getTargetData().getTypeSizeInBits(EltTy);
247 
248   // In some cases the bitfield may straddle two memory locations.
249   // Currently we load the entire bitfield, then do the magic to
250   // sign-extend it if necessary. This results in somewhat more code
251   // than necessary for the common case (one load), since two shifts
252   // accomplish both the masking and sign extension.
253   unsigned LowBits = std::min(BitfieldSize, EltTySize - StartBit);
254   llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "tmp");
255 
256   // Shift to proper location.
257   if (StartBit)
258     Val = Builder.CreateLShr(Val, llvm::ConstantInt::get(EltTy, StartBit),
259                              "bf.lo");
260 
261   // Mask off unused bits.
262   llvm::Constant *LowMask =
263     llvm::ConstantInt::get(llvm::APInt::getLowBitsSet(EltTySize, LowBits));
264   Val = Builder.CreateAnd(Val, LowMask, "bf.lo.cleared");
265 
266   // Fetch the high bits if necessary.
267   if (LowBits < BitfieldSize) {
268     unsigned HighBits = BitfieldSize - LowBits;
269     llvm::Value *HighPtr =
270       Builder.CreateGEP(Ptr, llvm::ConstantInt::get(llvm::Type::Int32Ty, 1),
271                         "bf.ptr.hi");
272     llvm::Value *HighVal = Builder.CreateLoad(HighPtr,
273                                               LV.isVolatileQualified(),
274                                               "tmp");
275 
276     // Mask off unused bits.
277     llvm::Constant *HighMask =
278       llvm::ConstantInt::get(llvm::APInt::getLowBitsSet(EltTySize, HighBits));
279     HighVal = Builder.CreateAnd(HighVal, HighMask, "bf.lo.cleared");
280 
281     // Shift to proper location and or in to bitfield value.
282     HighVal = Builder.CreateShl(HighVal,
283                                 llvm::ConstantInt::get(EltTy, LowBits));
284     Val = Builder.CreateOr(Val, HighVal, "bf.val");
285   }
286 
287   // Sign extend if necessary.
288   if (LV.isBitfieldSigned()) {
289     llvm::Value *ExtraBits = llvm::ConstantInt::get(EltTy,
290                                                     EltTySize - BitfieldSize);
291     Val = Builder.CreateAShr(Builder.CreateShl(Val, ExtraBits),
292                              ExtraBits, "bf.val.sext");
293   }
294 
295   // The bitfield type and the normal type differ when the storage sizes
296   // differ (currently just _Bool).
297   Val = Builder.CreateIntCast(Val, ConvertType(ExprType), false, "tmp");
298 
299   return RValue::get(Val);
300 }
301 
302 RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
303                                                     QualType ExprType) {
304   return EmitObjCPropertyGet(LV.getPropertyRefExpr());
305 }
306 
307 RValue CodeGenFunction::EmitLoadOfKVCRefLValue(LValue LV,
308                                                QualType ExprType) {
309   return EmitObjCPropertyGet(LV.getKVCRefExpr());
310 }
311 
312 // If this is a reference to a subset of the elements of a vector, either
313 // shuffle the input or extract/insert them as appropriate.
314 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV,
315                                                          QualType ExprType) {
316   llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(),
317                                         LV.isVolatileQualified(), "tmp");
318 
319   const llvm::Constant *Elts = LV.getExtVectorElts();
320 
321   // If the result of the expression is a non-vector type, we must be
322   // extracting a single element.  Just codegen as an extractelement.
323   const VectorType *ExprVT = ExprType->getAsVectorType();
324   if (!ExprVT) {
325     unsigned InIdx = getAccessedFieldNo(0, Elts);
326     llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
327     return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
328   }
329 
330   // If the source and destination have the same number of elements, use a
331   // vector shuffle instead of insert/extracts.
332   unsigned NumResultElts = ExprVT->getNumElements();
333   unsigned NumSourceElts =
334     cast<llvm::VectorType>(Vec->getType())->getNumElements();
335 
336   if (NumResultElts == NumSourceElts) {
337     llvm::SmallVector<llvm::Constant*, 4> Mask;
338     for (unsigned i = 0; i != NumResultElts; ++i) {
339       unsigned InIdx = getAccessedFieldNo(i, Elts);
340       Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
341     }
342 
343     llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
344     Vec = Builder.CreateShuffleVector(Vec,
345                                       llvm::UndefValue::get(Vec->getType()),
346                                       MaskV, "tmp");
347     return RValue::get(Vec);
348   }
349 
350   // Start out with an undef of the result type.
351   llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
352 
353   // Extract/Insert each element of the result.
354   for (unsigned i = 0; i != NumResultElts; ++i) {
355     unsigned InIdx = getAccessedFieldNo(i, Elts);
356     llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
357     Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
358 
359     llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
360     Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
361   }
362 
363   return RValue::get(Result);
364 }
365 
366 
367 
368 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
369 /// lvalue, where both are guaranteed to the have the same type, and that type
370 /// is 'Ty'.
371 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
372                                              QualType Ty) {
373   if (!Dst.isSimple()) {
374     if (Dst.isVectorElt()) {
375       // Read/modify/write the vector, inserting the new element.
376       llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(),
377                                             Dst.isVolatileQualified(), "tmp");
378       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
379                                         Dst.getVectorIdx(), "vecins");
380       Builder.CreateStore(Vec, Dst.getVectorAddr(),Dst.isVolatileQualified());
381       return;
382     }
383 
384     // If this is an update of extended vector elements, insert them as
385     // appropriate.
386     if (Dst.isExtVectorElt())
387       return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty);
388 
389     if (Dst.isBitfield())
390       return EmitStoreThroughBitfieldLValue(Src, Dst, Ty);
391 
392     if (Dst.isPropertyRef())
393       return EmitStoreThroughPropertyRefLValue(Src, Dst, Ty);
394 
395     if (Dst.isKVCRef())
396       return EmitStoreThroughKVCRefLValue(Src, Dst, Ty);
397 
398     assert(0 && "Unknown LValue type");
399   }
400 
401   if (Dst.isObjCWeak()) {
402     // load of a __weak object.
403     llvm::Value *LvalueDst = Dst.getAddress();
404     llvm::Value *src = Src.getScalarVal();
405     CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
406     return;
407   }
408 
409   if (Dst.isObjCStrong()) {
410     // load of a __strong object.
411     llvm::Value *LvalueDst = Dst.getAddress();
412     llvm::Value *src = Src.getScalarVal();
413     if (Dst.isObjCIvar())
414       CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, LvalueDst);
415     else
416       CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst);
417     return;
418   }
419 
420   llvm::Value *DstAddr = Dst.getAddress();
421   assert(Src.isScalar() && "Can't emit an agg store with this method");
422   // FIXME: Handle volatility etc.
423   const llvm::Type *SrcTy = Src.getScalarVal()->getType();
424   const llvm::PointerType *DstPtr = cast<llvm::PointerType>(DstAddr->getType());
425   const llvm::Type *AddrTy = DstPtr->getElementType();
426   unsigned AS = DstPtr->getAddressSpace();
427 
428   if (AddrTy != SrcTy)
429     DstAddr = Builder.CreateBitCast(DstAddr,
430                                     llvm::PointerType::get(SrcTy, AS),
431                                     "storetmp");
432   Builder.CreateStore(Src.getScalarVal(), DstAddr, Dst.isVolatileQualified());
433 }
434 
435 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
436                                                      QualType Ty,
437                                                      llvm::Value **Result) {
438   unsigned StartBit = Dst.getBitfieldStartBit();
439   unsigned BitfieldSize = Dst.getBitfieldSize();
440   llvm::Value *Ptr = Dst.getBitfieldAddr();
441 
442   const llvm::Type *EltTy =
443     cast<llvm::PointerType>(Ptr->getType())->getElementType();
444   unsigned EltTySize = CGM.getTargetData().getTypeSizeInBits(EltTy);
445 
446   // Get the new value, cast to the appropriate type and masked to
447   // exactly the size of the bit-field.
448   llvm::Value *SrcVal = Src.getScalarVal();
449   llvm::Value *NewVal = Builder.CreateIntCast(SrcVal, EltTy, false, "tmp");
450   llvm::Constant *Mask =
451     llvm::ConstantInt::get(llvm::APInt::getLowBitsSet(EltTySize, BitfieldSize));
452   NewVal = Builder.CreateAnd(NewVal, Mask, "bf.value");
453 
454   // Return the new value of the bit-field, if requested.
455   if (Result) {
456     // Cast back to the proper type for result.
457     const llvm::Type *SrcTy = SrcVal->getType();
458     llvm::Value *SrcTrunc = Builder.CreateIntCast(NewVal, SrcTy, false,
459                                                   "bf.reload.val");
460 
461     // Sign extend if necessary.
462     if (Dst.isBitfieldSigned()) {
463       unsigned SrcTySize = CGM.getTargetData().getTypeSizeInBits(SrcTy);
464       llvm::Value *ExtraBits = llvm::ConstantInt::get(SrcTy,
465                                                       SrcTySize - BitfieldSize);
466       SrcTrunc = Builder.CreateAShr(Builder.CreateShl(SrcTrunc, ExtraBits),
467                                     ExtraBits, "bf.reload.sext");
468     }
469 
470     *Result = SrcTrunc;
471   }
472 
473   // In some cases the bitfield may straddle two memory locations.
474   // Emit the low part first and check to see if the high needs to be
475   // done.
476   unsigned LowBits = std::min(BitfieldSize, EltTySize - StartBit);
477   llvm::Value *LowVal = Builder.CreateLoad(Ptr, Dst.isVolatileQualified(),
478                                            "bf.prev.low");
479 
480   // Compute the mask for zero-ing the low part of this bitfield.
481   llvm::Constant *InvMask =
482     llvm::ConstantInt::get(~llvm::APInt::getBitsSet(EltTySize, StartBit,
483                                                     StartBit + LowBits));
484 
485   // Compute the new low part as
486   //   LowVal = (LowVal & InvMask) | (NewVal << StartBit),
487   // with the shift of NewVal implicitly stripping the high bits.
488   llvm::Value *NewLowVal =
489     Builder.CreateShl(NewVal, llvm::ConstantInt::get(EltTy, StartBit),
490                       "bf.value.lo");
491   LowVal = Builder.CreateAnd(LowVal, InvMask, "bf.prev.lo.cleared");
492   LowVal = Builder.CreateOr(LowVal, NewLowVal, "bf.new.lo");
493 
494   // Write back.
495   Builder.CreateStore(LowVal, Ptr, Dst.isVolatileQualified());
496 
497   // If the low part doesn't cover the bitfield emit a high part.
498   if (LowBits < BitfieldSize) {
499     unsigned HighBits = BitfieldSize - LowBits;
500     llvm::Value *HighPtr =
501       Builder.CreateGEP(Ptr, llvm::ConstantInt::get(llvm::Type::Int32Ty, 1),
502                         "bf.ptr.hi");
503     llvm::Value *HighVal = Builder.CreateLoad(HighPtr,
504                                               Dst.isVolatileQualified(),
505                                               "bf.prev.hi");
506 
507     // Compute the mask for zero-ing the high part of this bitfield.
508     llvm::Constant *InvMask =
509       llvm::ConstantInt::get(~llvm::APInt::getLowBitsSet(EltTySize, HighBits));
510 
511     // Compute the new high part as
512     //   HighVal = (HighVal & InvMask) | (NewVal lshr LowBits),
513     // where the high bits of NewVal have already been cleared and the
514     // shift stripping the low bits.
515     llvm::Value *NewHighVal =
516       Builder.CreateLShr(NewVal, llvm::ConstantInt::get(EltTy, LowBits),
517                         "bf.value.high");
518     HighVal = Builder.CreateAnd(HighVal, InvMask, "bf.prev.hi.cleared");
519     HighVal = Builder.CreateOr(HighVal, NewHighVal, "bf.new.hi");
520 
521     // Write back.
522     Builder.CreateStore(HighVal, HighPtr, Dst.isVolatileQualified());
523   }
524 }
525 
526 void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
527                                                         LValue Dst,
528                                                         QualType Ty) {
529   EmitObjCPropertySet(Dst.getPropertyRefExpr(), Src);
530 }
531 
532 void CodeGenFunction::EmitStoreThroughKVCRefLValue(RValue Src,
533                                                    LValue Dst,
534                                                    QualType Ty) {
535   EmitObjCPropertySet(Dst.getKVCRefExpr(), Src);
536 }
537 
538 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
539                                                                LValue Dst,
540                                                                QualType Ty) {
541   // This access turns into a read/modify/write of the vector.  Load the input
542   // value now.
543   llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(),
544                                         Dst.isVolatileQualified(), "tmp");
545   const llvm::Constant *Elts = Dst.getExtVectorElts();
546 
547   llvm::Value *SrcVal = Src.getScalarVal();
548 
549   if (const VectorType *VTy = Ty->getAsVectorType()) {
550     unsigned NumSrcElts = VTy->getNumElements();
551 
552     // Extract/Insert each element.
553     for (unsigned i = 0; i != NumSrcElts; ++i) {
554       llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
555       Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp");
556 
557       unsigned Idx = getAccessedFieldNo(i, Elts);
558       llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx);
559       Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp");
560     }
561   } else {
562     // If the Src is a scalar (not a vector) it must be updating one element.
563     unsigned InIdx = getAccessedFieldNo(0, Elts);
564     llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
565     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
566   }
567 
568   Builder.CreateStore(Vec, Dst.getExtVectorAddr(), Dst.isVolatileQualified());
569 }
570 
571 /// SetVarDeclObjCAttribute - Set __weak/__strong attributes into the LValue
572 /// object.
573 static void SetVarDeclObjCAttribute(ASTContext &Ctx, const Decl *VD,
574                                     const QualType &Ty, LValue &LV)
575 {
576   if (const ObjCGCAttr *A = VD->getAttr<ObjCGCAttr>()) {
577     ObjCGCAttr::GCAttrTypes attrType = A->getType();
578     LValue::SetObjCType(attrType == ObjCGCAttr::Weak,
579                         attrType == ObjCGCAttr::Strong, LV);
580   }
581   else if (Ctx.getLangOptions().ObjC1 &&
582            Ctx.getLangOptions().getGCMode() != LangOptions::NonGC) {
583     // Default behavious under objective-c's gc is for objective-c pointers
584     // be treated as though they were declared as __strong.
585     if (Ctx.isObjCObjectPointerType(Ty))
586       LValue::SetObjCType(false, true, LV);
587   }
588 }
589 
590 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
591   const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
592 
593   if (VD && (VD->isBlockVarDecl() || isa<ParmVarDecl>(VD) ||
594         isa<ImplicitParamDecl>(VD))) {
595     LValue LV;
596     if (VD->getStorageClass() == VarDecl::Extern) {
597       LV = LValue::MakeAddr(CGM.GetAddrOfGlobalVar(VD),
598                             E->getType().getCVRQualifiers());
599     }
600     else {
601       llvm::Value *V = LocalDeclMap[VD];
602       assert(V && "BlockVarDecl not entered in LocalDeclMap?");
603       LV = LValue::MakeAddr(V, E->getType().getCVRQualifiers());
604     }
605     if (VD->isBlockVarDecl() &&
606         (VD->getStorageClass() == VarDecl::Static ||
607          VD->getStorageClass() == VarDecl::Extern))
608       SetVarDeclObjCAttribute(getContext(), VD, E->getType(), LV);
609     return LV;
610   } else if (VD && VD->isFileVarDecl()) {
611     LValue LV = LValue::MakeAddr(CGM.GetAddrOfGlobalVar(VD),
612                                  E->getType().getCVRQualifiers());
613     SetVarDeclObjCAttribute(getContext(), VD, E->getType(), LV);
614     return LV;
615   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
616     return LValue::MakeAddr(CGM.GetAddrOfFunction(FD),
617                             E->getType().getCVRQualifiers());
618   }
619   else if (const ImplicitParamDecl *IPD =
620       dyn_cast<ImplicitParamDecl>(E->getDecl())) {
621     llvm::Value *V = LocalDeclMap[IPD];
622     assert(V && "BlockVarDecl not entered in LocalDeclMap?");
623     return LValue::MakeAddr(V, E->getType().getCVRQualifiers());
624   }
625   assert(0 && "Unimp declref");
626   //an invalid LValue, but the assert will
627   //ensure that this point is never reached.
628   return LValue();
629 }
630 
631 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
632   // __extension__ doesn't affect lvalue-ness.
633   if (E->getOpcode() == UnaryOperator::Extension)
634     return EmitLValue(E->getSubExpr());
635 
636   QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
637   switch (E->getOpcode()) {
638   default: assert(0 && "Unknown unary operator lvalue!");
639   case UnaryOperator::Deref:
640     return LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()),
641                             ExprTy->getAsPointerType()->getPointeeType()
642                                     .getCVRQualifiers());
643   case UnaryOperator::Real:
644   case UnaryOperator::Imag:
645     LValue LV = EmitLValue(E->getSubExpr());
646     unsigned Idx = E->getOpcode() == UnaryOperator::Imag;
647     return LValue::MakeAddr(Builder.CreateStructGEP(LV.getAddress(),
648                                                     Idx, "idx"),
649                             ExprTy.getCVRQualifiers());
650   }
651 }
652 
653 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
654   return LValue::MakeAddr(CGM.GetAddrOfConstantStringFromLiteral(E), 0);
655 }
656 
657 LValue CodeGenFunction::EmitPredefinedFunctionName(unsigned Type) {
658   std::string GlobalVarName;
659 
660   switch (Type) {
661     default:
662       assert(0 && "Invalid type");
663     case PredefinedExpr::Func:
664       GlobalVarName = "__func__.";
665       break;
666     case PredefinedExpr::Function:
667       GlobalVarName = "__FUNCTION__.";
668       break;
669     case PredefinedExpr::PrettyFunction:
670       // FIXME:: Demangle C++ method names
671       GlobalVarName = "__PRETTY_FUNCTION__.";
672       break;
673   }
674 
675   std::string FunctionName;
676   if(const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurFuncDecl)) {
677     FunctionName = FD->getNameAsString();
678   } else {
679     // Just get the mangled name.
680     FunctionName = CurFn->getName();
681   }
682 
683   GlobalVarName += FunctionName;
684   llvm::Constant *C =
685     CGM.GetAddrOfConstantCString(FunctionName, GlobalVarName.c_str());
686   return LValue::MakeAddr(C, 0);
687 }
688 
689 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
690   switch (E->getIdentType()) {
691   default:
692     return EmitUnsupportedLValue(E, "predefined expression");
693   case PredefinedExpr::Func:
694   case PredefinedExpr::Function:
695   case PredefinedExpr::PrettyFunction:
696     return EmitPredefinedFunctionName(E->getIdentType());
697   }
698 }
699 
700 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
701   // The index must always be an integer, which is not an aggregate.  Emit it.
702   llvm::Value *Idx = EmitScalarExpr(E->getIdx());
703 
704   // If the base is a vector type, then we are forming a vector element lvalue
705   // with this subscript.
706   if (E->getBase()->getType()->isVectorType()) {
707     // Emit the vector as an lvalue to get its address.
708     LValue LHS = EmitLValue(E->getBase());
709     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
710     // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
711     return LValue::MakeVectorElt(LHS.getAddress(), Idx,
712       E->getBase()->getType().getCVRQualifiers());
713   }
714 
715   // The base must be a pointer, which is not an aggregate.  Emit it.
716   llvm::Value *Base = EmitScalarExpr(E->getBase());
717 
718   // Extend or truncate the index type to 32 or 64-bits.
719   QualType IdxTy  = E->getIdx()->getType();
720   bool IdxSigned = IdxTy->isSignedIntegerType();
721   unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
722   if (IdxBitwidth != LLVMPointerWidth)
723     Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
724                                 IdxSigned, "idxprom");
725 
726   // We know that the pointer points to a type of the correct size, unless the
727   // size is a VLA.
728   if (const VariableArrayType *VAT =
729         getContext().getAsVariableArrayType(E->getType())) {
730     llvm::Value *VLASize = VLASizeMap[VAT];
731 
732     Idx = Builder.CreateMul(Idx, VLASize);
733 
734     QualType BaseType = getContext().getBaseElementType(VAT);
735 
736     uint64_t BaseTypeSize = getContext().getTypeSize(BaseType) / 8;
737     Idx = Builder.CreateUDiv(Idx,
738                              llvm::ConstantInt::get(Idx->getType(),
739                                                     BaseTypeSize));
740   }
741 
742   QualType ExprTy = getContext().getCanonicalType(E->getBase()->getType());
743 
744   return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"),
745                           ExprTy->getAsPointerType()->getPointeeType()
746                                .getCVRQualifiers());
747 }
748 
749 static
750 llvm::Constant *GenerateConstantVector(llvm::SmallVector<unsigned, 4> &Elts) {
751   llvm::SmallVector<llvm::Constant *, 4> CElts;
752 
753   for (unsigned i = 0, e = Elts.size(); i != e; ++i)
754     CElts.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, Elts[i]));
755 
756   return llvm::ConstantVector::get(&CElts[0], CElts.size());
757 }
758 
759 LValue CodeGenFunction::
760 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
761   // Emit the base vector as an l-value.
762   LValue Base = EmitLValue(E->getBase());
763 
764   // Encode the element access list into a vector of unsigned indices.
765   llvm::SmallVector<unsigned, 4> Indices;
766   E->getEncodedElementAccess(Indices);
767 
768   if (Base.isSimple()) {
769     llvm::Constant *CV = GenerateConstantVector(Indices);
770     return LValue::MakeExtVectorElt(Base.getAddress(), CV,
771                                    E->getBase()->getType().getCVRQualifiers());
772   }
773   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
774 
775   llvm::Constant *BaseElts = Base.getExtVectorElts();
776   llvm::SmallVector<llvm::Constant *, 4> CElts;
777 
778   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
779     if (isa<llvm::ConstantAggregateZero>(BaseElts))
780       CElts.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
781     else
782       CElts.push_back(BaseElts->getOperand(Indices[i]));
783   }
784   llvm::Constant *CV = llvm::ConstantVector::get(&CElts[0], CElts.size());
785   return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV,
786                                   E->getBase()->getType().getCVRQualifiers());
787 }
788 
789 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
790   bool isUnion = false;
791   bool isIvar = false;
792   Expr *BaseExpr = E->getBase();
793   llvm::Value *BaseValue = NULL;
794   unsigned CVRQualifiers=0;
795 
796   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
797   if (E->isArrow()) {
798     BaseValue = EmitScalarExpr(BaseExpr);
799     const PointerType *PTy =
800       cast<PointerType>(getContext().getCanonicalType(BaseExpr->getType()));
801     if (PTy->getPointeeType()->isUnionType())
802       isUnion = true;
803     CVRQualifiers = PTy->getPointeeType().getCVRQualifiers();
804   }
805   else if (BaseExpr->getStmtClass() == Expr::ObjCPropertyRefExprClass ||
806            BaseExpr->getStmtClass() == Expr::ObjCKVCRefExprClass) {
807     RValue RV = EmitObjCPropertyGet(BaseExpr);
808     BaseValue = RV.getAggregateAddr();
809     if (BaseExpr->getType()->isUnionType())
810       isUnion = true;
811     CVRQualifiers = BaseExpr->getType().getCVRQualifiers();
812   }
813   else {
814     LValue BaseLV = EmitLValue(BaseExpr);
815     if (BaseLV.isObjCIvar())
816       isIvar = true;
817     // FIXME: this isn't right for bitfields.
818     BaseValue = BaseLV.getAddress();
819     if (BaseExpr->getType()->isUnionType())
820       isUnion = true;
821     CVRQualifiers = BaseExpr->getType().getCVRQualifiers();
822   }
823 
824   FieldDecl *Field = dyn_cast<FieldDecl>(E->getMemberDecl());
825   // FIXME: Handle non-field member expressions
826   assert(Field && "No code generation for non-field member references");
827   LValue MemExpLV =  EmitLValueForField(BaseValue, Field, isUnion, CVRQualifiers);
828   LValue::SetObjCIvar(MemExpLV, isIvar);
829   return MemExpLV;
830 }
831 
832 LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value* BaseValue,
833                                               FieldDecl* Field,
834                                               unsigned CVRQualifiers,
835                                               unsigned idx) {
836   // FIXME: CodeGenTypes should expose a method to get the appropriate
837   // type for FieldTy (the appropriate type is ABI-dependent).
838   const llvm::Type *FieldTy = CGM.getTypes().ConvertTypeForMem(Field->getType());
839   const llvm::PointerType *BaseTy =
840   cast<llvm::PointerType>(BaseValue->getType());
841   unsigned AS = BaseTy->getAddressSpace();
842   BaseValue = Builder.CreateBitCast(BaseValue,
843                                     llvm::PointerType::get(FieldTy, AS),
844                                     "tmp");
845   llvm::Value *V = Builder.CreateGEP(BaseValue,
846                               llvm::ConstantInt::get(llvm::Type::Int32Ty, idx),
847                               "tmp");
848 
849   CodeGenTypes::BitFieldInfo bitFieldInfo =
850     CGM.getTypes().getBitFieldInfo(Field);
851   return LValue::MakeBitfield(V, bitFieldInfo.Begin, bitFieldInfo.Size,
852                               Field->getType()->isSignedIntegerType(),
853                             Field->getType().getCVRQualifiers()|CVRQualifiers);
854 }
855 
856 LValue CodeGenFunction::EmitLValueForField(llvm::Value* BaseValue,
857                                            FieldDecl* Field,
858                                            bool isUnion,
859                                            unsigned CVRQualifiers)
860 {
861   unsigned idx = CGM.getTypes().getLLVMFieldNo(Field);
862 
863   if (Field->isBitField())
864     return EmitLValueForBitfield(BaseValue, Field, CVRQualifiers, idx);
865 
866   llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp");
867 
868   // Match union field type.
869   if (isUnion) {
870     const llvm::Type *FieldTy =
871       CGM.getTypes().ConvertTypeForMem(Field->getType());
872     const llvm::PointerType * BaseTy =
873       cast<llvm::PointerType>(BaseValue->getType());
874     unsigned AS = BaseTy->getAddressSpace();
875     V = Builder.CreateBitCast(V,
876                               llvm::PointerType::get(FieldTy, AS),
877                               "tmp");
878   }
879 
880   LValue LV =
881     LValue::MakeAddr(V,
882                      Field->getType().getCVRQualifiers()|CVRQualifiers);
883   if (const ObjCGCAttr *A = Field->getAttr<ObjCGCAttr>()) {
884     ObjCGCAttr::GCAttrTypes attrType = A->getType();
885     // __weak attribute on a field is ignored.
886     LValue::SetObjCType(false, attrType == ObjCGCAttr::Strong, LV);
887   }
888   else if (CGM.getLangOptions().ObjC1 &&
889            CGM.getLangOptions().getGCMode() != LangOptions::NonGC) {
890     QualType ExprTy = Field->getType();
891     if (getContext().isObjCObjectPointerType(ExprTy))
892       LValue::SetObjCType(false, true, LV);
893   }
894   return LV;
895 }
896 
897 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr* E)
898 {
899   const llvm::Type *LTy = ConvertType(E->getType());
900   llvm::Value *DeclPtr = CreateTempAlloca(LTy, ".compoundliteral");
901 
902   const Expr* InitExpr = E->getInitializer();
903   LValue Result = LValue::MakeAddr(DeclPtr, E->getType().getCVRQualifiers());
904 
905   if (E->getType()->isComplexType()) {
906     EmitComplexExprIntoAddr(InitExpr, DeclPtr, false);
907   } else if (hasAggregateLLVMType(E->getType())) {
908     EmitAnyExpr(InitExpr, DeclPtr, false);
909   } else {
910     EmitStoreThroughLValue(EmitAnyExpr(InitExpr), Result, E->getType());
911   }
912 
913   return Result;
914 }
915 
916 //===--------------------------------------------------------------------===//
917 //                             Expression Emission
918 //===--------------------------------------------------------------------===//
919 
920 
921 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
922   if (const ImplicitCastExpr *IcExpr =
923       dyn_cast<const ImplicitCastExpr>(E->getCallee()))
924     if (const DeclRefExpr *DRExpr =
925         dyn_cast<const DeclRefExpr>(IcExpr->getSubExpr()))
926       if (const FunctionDecl *FDecl =
927           dyn_cast<const FunctionDecl>(DRExpr->getDecl()))
928         if (unsigned builtinID = FDecl->getIdentifier()->getBuiltinID())
929           return EmitBuiltinExpr(builtinID, E);
930 
931   if (E->getCallee()->getType()->isBlockPointerType())
932     return EmitUnsupportedRValue(E, "block pointer reference");
933 
934   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
935   return EmitCallExpr(Callee, E->getCallee()->getType(),
936                       E->arg_begin(), E->arg_end());
937 }
938 
939 RValue CodeGenFunction::EmitCallExpr(Expr *FnExpr,
940                                      CallExpr::const_arg_iterator ArgBeg,
941                                      CallExpr::const_arg_iterator ArgEnd) {
942 
943   llvm::Value *Callee = EmitScalarExpr(FnExpr);
944   return EmitCallExpr(Callee, FnExpr->getType(), ArgBeg, ArgEnd);
945 }
946 
947 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
948   // Can only get l-value for binary operator expressions which are a
949   // simple assignment of aggregate type.
950   if (E->getOpcode() != BinaryOperator::Assign)
951     return EmitUnsupportedLValue(E, "binary l-value expression");
952 
953   llvm::Value *Temp = CreateTempAlloca(ConvertType(E->getType()));
954   EmitAggExpr(E, Temp, false);
955   // FIXME: Are these qualifiers correct?
956   return LValue::MakeAddr(Temp, E->getType().getCVRQualifiers());
957 }
958 
959 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
960   // Can only get l-value for call expression returning aggregate type
961   RValue RV = EmitCallExpr(E);
962   // FIXME: can this be volatile?
963   return LValue::MakeAddr(RV.getAggregateAddr(),
964                           E->getType().getCVRQualifiers());
965 }
966 
967 LValue
968 CodeGenFunction::EmitCXXConditionDeclLValue(const CXXConditionDeclExpr *E) {
969   EmitLocalBlockVarDecl(*E->getVarDecl());
970   return EmitDeclRefLValue(E);
971 }
972 
973 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
974   // Can only get l-value for message expression returning aggregate type
975   RValue RV = EmitObjCMessageExpr(E);
976   // FIXME: can this be volatile?
977   return LValue::MakeAddr(RV.getAggregateAddr(),
978                           E->getType().getCVRQualifiers());
979 }
980 
981 llvm::Value *CodeGenFunction::EmitIvarOffset(ObjCInterfaceDecl *Interface,
982                                              const ObjCIvarDecl *Ivar) {
983   // Objective-C objects are traditionally C structures with their layout
984   // defined at compile-time.  In some implementations, their layout is not
985   // defined until run time in order to allow instance variables to be added to
986   // a class without recompiling all of the subclasses.  If this is the case
987   // then the CGObjCRuntime subclass must return true to LateBoundIvars and
988   // implement the lookup itself.
989   if (CGM.getObjCRuntime().LateBoundIVars())
990     assert(0 && "late-bound ivars are unsupported");
991 
992   const llvm::Type *InterfaceLTy =
993     CGM.getTypes().ConvertType(getContext().getObjCInterfaceType(Interface));
994   const llvm::StructLayout *Layout =
995     CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceLTy));
996   FieldDecl *Field = Interface->lookupFieldDeclForIvar(getContext(), Ivar);
997   uint64_t Offset =
998     Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
999 
1000   return llvm::ConstantInt::get(CGM.getTypes().ConvertType(getContext().LongTy),
1001                                 Offset);
1002 }
1003 
1004 LValue CodeGenFunction::EmitLValueForIvar(llvm::Value *BaseValue,
1005                                           const ObjCIvarDecl *Ivar,
1006                                           const FieldDecl *Field,
1007                                           unsigned CVRQualifiers) {
1008   // See comment in EmitIvarOffset.
1009   if (CGM.getObjCRuntime().LateBoundIVars())
1010     assert(0 && "late-bound ivars are unsupported");
1011   // TODO:  Add a special case for isa (index 0)
1012   unsigned Index = CGM.getTypes().getLLVMFieldNo(Field);
1013 
1014   if (Ivar->isBitField()) {
1015     return EmitLValueForBitfield(BaseValue, const_cast<FieldDecl *>(Field),
1016                                  CVRQualifiers, Index);
1017   }
1018   llvm::Value *V = Builder.CreateStructGEP(BaseValue, Index, "tmp");
1019   LValue LV = LValue::MakeAddr(V, Ivar->getType().getCVRQualifiers()|CVRQualifiers);
1020   SetVarDeclObjCAttribute(getContext(), Ivar, Ivar->getType(), LV);
1021   LValue::SetObjCIvar(LV, true);
1022   return LV;
1023 }
1024 
1025 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
1026   // FIXME: A lot of the code below could be shared with EmitMemberExpr.
1027   llvm::Value *BaseValue = 0;
1028   const Expr *BaseExpr = E->getBase();
1029   unsigned CVRQualifiers = 0;
1030   if (E->isArrow()) {
1031     BaseValue = EmitScalarExpr(BaseExpr);
1032     const PointerType *PTy =
1033       cast<PointerType>(getContext().getCanonicalType(BaseExpr->getType()));
1034     CVRQualifiers = PTy->getPointeeType().getCVRQualifiers();
1035   } else {
1036     LValue BaseLV = EmitLValue(BaseExpr);
1037     // FIXME: this isn't right for bitfields.
1038     BaseValue = BaseLV.getAddress();
1039     CVRQualifiers = BaseExpr->getType().getCVRQualifiers();
1040   }
1041 
1042   return EmitLValueForIvar(BaseValue, E->getDecl(),
1043                            getContext().getFieldDecl(E), CVRQualifiers);
1044 }
1045 
1046 LValue
1047 CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
1048   // This is a special l-value that just issues sends when we load or
1049   // store through it.
1050   return LValue::MakePropertyRef(E, E->getType().getCVRQualifiers());
1051 }
1052 
1053 LValue
1054 CodeGenFunction::EmitObjCKVCRefLValue(const ObjCKVCRefExpr *E) {
1055   // This is a special l-value that just issues sends when we load or
1056   // store through it.
1057   return LValue::MakeKVCRef(E, E->getType().getCVRQualifiers());
1058 }
1059 
1060 LValue
1061 CodeGenFunction::EmitObjCSuperExpr(const ObjCSuperExpr *E) {
1062   return EmitUnsupportedLValue(E, "use of super");
1063 }
1064 
1065 RValue CodeGenFunction::EmitCallExpr(llvm::Value *Callee, QualType CalleeType,
1066                                      CallExpr::const_arg_iterator ArgBeg,
1067                                      CallExpr::const_arg_iterator ArgEnd) {
1068   // Get the actual function type. The callee type will always be a
1069   // pointer to function type or a block pointer type.
1070   QualType ResultType;
1071   if (const BlockPointerType *BPT = dyn_cast<BlockPointerType>(CalleeType)) {
1072     ResultType = BPT->getPointeeType()->getAsFunctionType()->getResultType();
1073   } else {
1074     assert(CalleeType->isFunctionPointerType() &&
1075            "Call must have function pointer type!");
1076     QualType FnType = CalleeType->getAsPointerType()->getPointeeType();
1077     ResultType = FnType->getAsFunctionType()->getResultType();
1078   }
1079 
1080   CallArgList Args;
1081   for (CallExpr::const_arg_iterator I = ArgBeg; I != ArgEnd; ++I)
1082     Args.push_back(std::make_pair(EmitAnyExprToTemp(*I),
1083                                   I->getType()));
1084 
1085   return EmitCall(Callee, ResultType, Args);
1086 }
1087