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