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