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 "CGCXXABI.h"
18 #include "CGDebugInfo.h"
19 #include "CGRecordLayout.h"
20 #include "CGObjCRuntime.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "llvm/Intrinsics.h"
24 #include "clang/Frontend/CodeGenOptions.h"
25 #include "llvm/Target/TargetData.h"
26 using namespace clang;
27 using namespace CodeGen;
28 
29 //===--------------------------------------------------------------------===//
30 //                        Miscellaneous Helper Methods
31 //===--------------------------------------------------------------------===//
32 
33 llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
34   unsigned addressSpace =
35     cast<llvm::PointerType>(value->getType())->getAddressSpace();
36 
37   const llvm::PointerType *destType = Int8PtrTy;
38   if (addressSpace)
39     destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
40 
41   if (value->getType() == destType) return value;
42   return Builder.CreateBitCast(value, destType);
43 }
44 
45 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
46 /// block.
47 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
48                                                     const llvm::Twine &Name) {
49   if (!Builder.isNamePreserving())
50     return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt);
51   return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
52 }
53 
54 void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
55                                      llvm::Value *Init) {
56   llvm::StoreInst *Store = new llvm::StoreInst(Init, Var);
57   llvm::BasicBlock *Block = AllocaInsertPt->getParent();
58   Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
59 }
60 
61 llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
62                                                 const llvm::Twine &Name) {
63   llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
64   // FIXME: Should we prefer the preferred type alignment here?
65   CharUnits Align = getContext().getTypeAlignInChars(Ty);
66   Alloc->setAlignment(Align.getQuantity());
67   return Alloc;
68 }
69 
70 llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
71                                                  const llvm::Twine &Name) {
72   llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
73   // FIXME: Should we prefer the preferred type alignment here?
74   CharUnits Align = getContext().getTypeAlignInChars(Ty);
75   Alloc->setAlignment(Align.getQuantity());
76   return Alloc;
77 }
78 
79 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
80 /// expression and compare the result against zero, returning an Int1Ty value.
81 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
82   if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
83     llvm::Value *MemPtr = EmitScalarExpr(E);
84     return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
85   }
86 
87   QualType BoolTy = getContext().BoolTy;
88   if (!E->getType()->isAnyComplexType())
89     return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
90 
91   return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
92 }
93 
94 /// EmitIgnoredExpr - Emit code to compute the specified expression,
95 /// ignoring the result.
96 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
97   if (E->isRValue())
98     return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
99 
100   // Just emit it as an l-value and drop the result.
101   EmitLValue(E);
102 }
103 
104 /// EmitAnyExpr - Emit code to compute the specified expression which
105 /// can have any type.  The result is returned as an RValue struct.
106 /// If this is an aggregate expression, AggSlot indicates where the
107 /// result should be returned.
108 RValue CodeGenFunction::EmitAnyExpr(const Expr *E, AggValueSlot AggSlot,
109                                     bool IgnoreResult) {
110   if (!hasAggregateLLVMType(E->getType()))
111     return RValue::get(EmitScalarExpr(E, IgnoreResult));
112   else if (E->getType()->isAnyComplexType())
113     return RValue::getComplex(EmitComplexExpr(E, IgnoreResult, IgnoreResult));
114 
115   EmitAggExpr(E, AggSlot, IgnoreResult);
116   return AggSlot.asRValue();
117 }
118 
119 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
120 /// always be accessible even if no aggregate location is provided.
121 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
122   AggValueSlot AggSlot = AggValueSlot::ignored();
123 
124   if (hasAggregateLLVMType(E->getType()) &&
125       !E->getType()->isAnyComplexType())
126     AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
127   return EmitAnyExpr(E, AggSlot);
128 }
129 
130 /// EmitAnyExprToMem - Evaluate an expression into a given memory
131 /// location.
132 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
133                                        llvm::Value *Location,
134                                        Qualifiers Quals,
135                                        bool IsInit) {
136   if (E->getType()->isAnyComplexType())
137     EmitComplexExprIntoAddr(E, Location, Quals.hasVolatile());
138   else if (hasAggregateLLVMType(E->getType()))
139     EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals, IsInit));
140   else {
141     RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
142     LValue LV = MakeAddrLValue(Location, E->getType());
143     EmitStoreThroughLValue(RV, LV);
144   }
145 }
146 
147 namespace {
148 /// \brief An adjustment to be made to the temporary created when emitting a
149 /// reference binding, which accesses a particular subobject of that temporary.
150   struct SubobjectAdjustment {
151     enum { DerivedToBaseAdjustment, FieldAdjustment } Kind;
152 
153     union {
154       struct {
155         const CastExpr *BasePath;
156         const CXXRecordDecl *DerivedClass;
157       } DerivedToBase;
158 
159       FieldDecl *Field;
160     };
161 
162     SubobjectAdjustment(const CastExpr *BasePath,
163                         const CXXRecordDecl *DerivedClass)
164       : Kind(DerivedToBaseAdjustment) {
165       DerivedToBase.BasePath = BasePath;
166       DerivedToBase.DerivedClass = DerivedClass;
167     }
168 
169     SubobjectAdjustment(FieldDecl *Field)
170       : Kind(FieldAdjustment) {
171       this->Field = Field;
172     }
173   };
174 }
175 
176 static llvm::Value *
177 CreateReferenceTemporary(CodeGenFunction& CGF, QualType Type,
178                          const NamedDecl *InitializedDecl) {
179   if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
180     if (VD->hasGlobalStorage()) {
181       llvm::SmallString<256> Name;
182       llvm::raw_svector_ostream Out(Name);
183       CGF.CGM.getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
184       Out.flush();
185 
186       const llvm::Type *RefTempTy = CGF.ConvertTypeForMem(Type);
187 
188       // Create the reference temporary.
189       llvm::GlobalValue *RefTemp =
190         new llvm::GlobalVariable(CGF.CGM.getModule(),
191                                  RefTempTy, /*isConstant=*/false,
192                                  llvm::GlobalValue::InternalLinkage,
193                                  llvm::Constant::getNullValue(RefTempTy),
194                                  Name.str());
195       return RefTemp;
196     }
197   }
198 
199   return CGF.CreateMemTemp(Type, "ref.tmp");
200 }
201 
202 static llvm::Value *
203 EmitExprForReferenceBinding(CodeGenFunction &CGF, const Expr *E,
204                             llvm::Value *&ReferenceTemporary,
205                             const CXXDestructorDecl *&ReferenceTemporaryDtor,
206                             QualType &ObjCARCReferenceLifetimeType,
207                             const NamedDecl *InitializedDecl) {
208   // Look through expressions for materialized temporaries (for now).
209   if (const MaterializeTemporaryExpr *M
210                                       = dyn_cast<MaterializeTemporaryExpr>(E)) {
211     // Objective-C++ ARC:
212     //   If we are binding a reference to a temporary that has ownership, we
213     //   need to perform retain/release operations on the temporary.
214     if (CGF.getContext().getLangOptions().ObjCAutoRefCount &&
215         E->getType()->isObjCLifetimeType() &&
216         (E->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
217          E->getType().getObjCLifetime() == Qualifiers::OCL_Weak ||
218          E->getType().getObjCLifetime() == Qualifiers::OCL_Autoreleasing))
219       ObjCARCReferenceLifetimeType = E->getType();
220 
221     E = M->GetTemporaryExpr();
222   }
223 
224   if (const CXXDefaultArgExpr *DAE = dyn_cast<CXXDefaultArgExpr>(E))
225     E = DAE->getExpr();
226 
227   if (const ExprWithCleanups *TE = dyn_cast<ExprWithCleanups>(E)) {
228     CodeGenFunction::RunCleanupsScope Scope(CGF);
229 
230     return EmitExprForReferenceBinding(CGF, TE->getSubExpr(),
231                                        ReferenceTemporary,
232                                        ReferenceTemporaryDtor,
233                                        ObjCARCReferenceLifetimeType,
234                                        InitializedDecl);
235   }
236 
237   if (const ObjCPropertyRefExpr *PRE =
238       dyn_cast<ObjCPropertyRefExpr>(E->IgnoreParenImpCasts()))
239     if (PRE->getGetterResultType()->isReferenceType())
240       E = PRE;
241 
242   RValue RV;
243   if (E->isGLValue()) {
244     // Emit the expression as an lvalue.
245     LValue LV = CGF.EmitLValue(E);
246     if (LV.isPropertyRef()) {
247       RV = CGF.EmitLoadOfPropertyRefLValue(LV);
248       return RV.getScalarVal();
249     }
250     if (LV.isSimple())
251       return LV.getAddress();
252 
253     // We have to load the lvalue.
254     RV = CGF.EmitLoadOfLValue(LV);
255   } else {
256     if (!ObjCARCReferenceLifetimeType.isNull()) {
257       ReferenceTemporary = CreateReferenceTemporary(CGF,
258                                                   ObjCARCReferenceLifetimeType,
259                                                     InitializedDecl);
260 
261 
262       LValue RefTempDst = CGF.MakeAddrLValue(ReferenceTemporary,
263                                              ObjCARCReferenceLifetimeType);
264 
265       CGF.EmitScalarInit(E, dyn_cast_or_null<ValueDecl>(InitializedDecl),
266                          RefTempDst, false);
267 
268       bool ExtendsLifeOfTemporary = false;
269       if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
270         if (Var->extendsLifetimeOfTemporary())
271           ExtendsLifeOfTemporary = true;
272       } else if (InitializedDecl && isa<FieldDecl>(InitializedDecl)) {
273         ExtendsLifeOfTemporary = true;
274       }
275 
276       if (!ExtendsLifeOfTemporary) {
277         // Since the lifetime of this temporary isn't going to be extended,
278         // we need to clean it up ourselves at the end of the full expression.
279         switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
280         case Qualifiers::OCL_None:
281         case Qualifiers::OCL_ExplicitNone:
282         case Qualifiers::OCL_Autoreleasing:
283           break;
284 
285         case Qualifiers::OCL_Strong:
286           CGF.PushARCReleaseCleanup(CGF.getARCCleanupKind(),
287                                     ObjCARCReferenceLifetimeType,
288                                     ReferenceTemporary,
289                                     /*Precise lifetime=*/false,
290                                     /*For full expression=*/true);
291           break;
292 
293         case Qualifiers::OCL_Weak:
294           CGF.PushARCWeakReleaseCleanup(NormalAndEHCleanup,
295                                         ObjCARCReferenceLifetimeType,
296                                         ReferenceTemporary,
297                                         /*For full expression=*/true);
298           break;
299         }
300 
301         ObjCARCReferenceLifetimeType = QualType();
302       }
303 
304       return ReferenceTemporary;
305     }
306 
307     llvm::SmallVector<SubobjectAdjustment, 2> Adjustments;
308     while (true) {
309       E = E->IgnoreParens();
310 
311       if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
312         if ((CE->getCastKind() == CK_DerivedToBase ||
313              CE->getCastKind() == CK_UncheckedDerivedToBase) &&
314             E->getType()->isRecordType()) {
315           E = CE->getSubExpr();
316           CXXRecordDecl *Derived
317             = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
318           Adjustments.push_back(SubobjectAdjustment(CE, Derived));
319           continue;
320         }
321 
322         if (CE->getCastKind() == CK_NoOp) {
323           E = CE->getSubExpr();
324           continue;
325         }
326       } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
327         if (!ME->isArrow() && ME->getBase()->isRValue()) {
328           assert(ME->getBase()->getType()->isRecordType());
329           if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
330             E = ME->getBase();
331             Adjustments.push_back(SubobjectAdjustment(Field));
332             continue;
333           }
334         }
335       }
336 
337       if (const OpaqueValueExpr *opaque = dyn_cast<OpaqueValueExpr>(E))
338         if (opaque->getType()->isRecordType())
339           return CGF.EmitOpaqueValueLValue(opaque).getAddress();
340 
341       // Nothing changed.
342       break;
343     }
344 
345     // Create a reference temporary if necessary.
346     AggValueSlot AggSlot = AggValueSlot::ignored();
347     if (CGF.hasAggregateLLVMType(E->getType()) &&
348         !E->getType()->isAnyComplexType()) {
349       ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
350                                                     InitializedDecl);
351       AggSlot = AggValueSlot::forAddr(ReferenceTemporary, Qualifiers(),
352                                       InitializedDecl != 0);
353     }
354 
355     if (InitializedDecl) {
356       // Get the destructor for the reference temporary.
357       if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
358         CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
359         if (!ClassDecl->hasTrivialDestructor())
360           ReferenceTemporaryDtor = ClassDecl->getDestructor();
361       }
362     }
363 
364     RV = CGF.EmitAnyExpr(E, AggSlot);
365 
366     // Check if need to perform derived-to-base casts and/or field accesses, to
367     // get from the temporary object we created (and, potentially, for which we
368     // extended the lifetime) to the subobject we're binding the reference to.
369     if (!Adjustments.empty()) {
370       llvm::Value *Object = RV.getAggregateAddr();
371       for (unsigned I = Adjustments.size(); I != 0; --I) {
372         SubobjectAdjustment &Adjustment = Adjustments[I-1];
373         switch (Adjustment.Kind) {
374         case SubobjectAdjustment::DerivedToBaseAdjustment:
375           Object =
376               CGF.GetAddressOfBaseClass(Object,
377                                         Adjustment.DerivedToBase.DerivedClass,
378                               Adjustment.DerivedToBase.BasePath->path_begin(),
379                               Adjustment.DerivedToBase.BasePath->path_end(),
380                                         /*NullCheckValue=*/false);
381           break;
382 
383         case SubobjectAdjustment::FieldAdjustment: {
384           LValue LV =
385             CGF.EmitLValueForField(Object, Adjustment.Field, 0);
386           if (LV.isSimple()) {
387             Object = LV.getAddress();
388             break;
389           }
390 
391           // For non-simple lvalues, we actually have to create a copy of
392           // the object we're binding to.
393           QualType T = Adjustment.Field->getType().getNonReferenceType()
394                                                   .getUnqualifiedType();
395           Object = CreateReferenceTemporary(CGF, T, InitializedDecl);
396           LValue TempLV = CGF.MakeAddrLValue(Object,
397                                              Adjustment.Field->getType());
398           CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV), TempLV);
399           break;
400         }
401 
402         }
403       }
404 
405       return Object;
406     }
407   }
408 
409   if (RV.isAggregate())
410     return RV.getAggregateAddr();
411 
412   // Create a temporary variable that we can bind the reference to.
413   ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
414                                                 InitializedDecl);
415 
416 
417   unsigned Alignment =
418     CGF.getContext().getTypeAlignInChars(E->getType()).getQuantity();
419   if (RV.isScalar())
420     CGF.EmitStoreOfScalar(RV.getScalarVal(), ReferenceTemporary,
421                           /*Volatile=*/false, Alignment, E->getType());
422   else
423     CGF.StoreComplexToAddr(RV.getComplexVal(), ReferenceTemporary,
424                            /*Volatile=*/false);
425   return ReferenceTemporary;
426 }
427 
428 RValue
429 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E,
430                                             const NamedDecl *InitializedDecl) {
431   llvm::Value *ReferenceTemporary = 0;
432   const CXXDestructorDecl *ReferenceTemporaryDtor = 0;
433   QualType ObjCARCReferenceLifetimeType;
434   llvm::Value *Value = EmitExprForReferenceBinding(*this, E, ReferenceTemporary,
435                                                    ReferenceTemporaryDtor,
436                                                    ObjCARCReferenceLifetimeType,
437                                                    InitializedDecl);
438   if (!ReferenceTemporaryDtor && ObjCARCReferenceLifetimeType.isNull())
439     return RValue::get(Value);
440 
441   // Make sure to call the destructor for the reference temporary.
442   const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl);
443   if (VD && VD->hasGlobalStorage()) {
444     if (ReferenceTemporaryDtor) {
445       llvm::Constant *DtorFn =
446         CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete);
447       EmitCXXGlobalDtorRegistration(DtorFn,
448                                     cast<llvm::Constant>(ReferenceTemporary));
449     } else {
450       assert(!ObjCARCReferenceLifetimeType.isNull());
451       // Note: We intentionally do not register a global "destructor" to
452       // release the object.
453     }
454 
455     return RValue::get(Value);
456   }
457 
458   if (ReferenceTemporaryDtor)
459     PushDestructorCleanup(ReferenceTemporaryDtor, ReferenceTemporary);
460   else {
461     switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
462     case Qualifiers::OCL_None:
463       llvm_unreachable("Not a reference temporary that needs to be deallocated");
464       break;
465 
466     case Qualifiers::OCL_ExplicitNone:
467     case Qualifiers::OCL_Autoreleasing:
468       // Nothing to do.
469       break;
470 
471     case Qualifiers::OCL_Strong:
472       PushARCReleaseCleanup(getARCCleanupKind(), ObjCARCReferenceLifetimeType,
473                             ReferenceTemporary,
474                             VD && VD->hasAttr<ObjCPreciseLifetimeAttr>());
475       break;
476 
477     case Qualifiers::OCL_Weak:
478       // __weak objects always get EH cleanups; otherwise, exceptions
479       // could cause really nasty crashes instead of mere leaks.
480       PushARCWeakReleaseCleanup(NormalAndEHCleanup,
481                                 ObjCARCReferenceLifetimeType,
482                                 ReferenceTemporary);
483       break;
484     }
485   }
486 
487   return RValue::get(Value);
488 }
489 
490 
491 /// getAccessedFieldNo - Given an encoded value and a result number, return the
492 /// input field number being accessed.
493 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
494                                              const llvm::Constant *Elts) {
495   if (isa<llvm::ConstantAggregateZero>(Elts))
496     return 0;
497 
498   return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue();
499 }
500 
501 void CodeGenFunction::EmitCheck(llvm::Value *Address, unsigned Size) {
502   if (!CatchUndefined)
503     return;
504 
505   // This needs to be to the standard address space.
506   Address = Builder.CreateBitCast(Address, Int8PtrTy);
507 
508   const llvm::Type *IntPtrT = IntPtrTy;
509   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, &IntPtrT, 1);
510 
511   // In time, people may want to control this and use a 1 here.
512   llvm::Value *Arg = Builder.getFalse();
513   llvm::Value *C = Builder.CreateCall2(F, Address, Arg);
514   llvm::BasicBlock *Cont = createBasicBlock();
515   llvm::BasicBlock *Check = createBasicBlock();
516   llvm::Value *NegativeOne = llvm::ConstantInt::get(IntPtrTy, -1ULL);
517   Builder.CreateCondBr(Builder.CreateICmpEQ(C, NegativeOne), Cont, Check);
518 
519   EmitBlock(Check);
520   Builder.CreateCondBr(Builder.CreateICmpUGE(C,
521                                         llvm::ConstantInt::get(IntPtrTy, Size)),
522                        Cont, getTrapBB());
523   EmitBlock(Cont);
524 }
525 
526 
527 CodeGenFunction::ComplexPairTy CodeGenFunction::
528 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
529                          bool isInc, bool isPre) {
530   ComplexPairTy InVal = LoadComplexFromAddr(LV.getAddress(),
531                                             LV.isVolatileQualified());
532 
533   llvm::Value *NextVal;
534   if (isa<llvm::IntegerType>(InVal.first->getType())) {
535     uint64_t AmountVal = isInc ? 1 : -1;
536     NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
537 
538     // Add the inc/dec to the real part.
539     NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
540   } else {
541     QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
542     llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
543     if (!isInc)
544       FVal.changeSign();
545     NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
546 
547     // Add the inc/dec to the real part.
548     NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
549   }
550 
551   ComplexPairTy IncVal(NextVal, InVal.second);
552 
553   // Store the updated result through the lvalue.
554   StoreComplexToAddr(IncVal, LV.getAddress(), LV.isVolatileQualified());
555 
556   // If this is a postinc, return the value read from memory, otherwise use the
557   // updated value.
558   return isPre ? IncVal : InVal;
559 }
560 
561 
562 //===----------------------------------------------------------------------===//
563 //                         LValue Expression Emission
564 //===----------------------------------------------------------------------===//
565 
566 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
567   if (Ty->isVoidType())
568     return RValue::get(0);
569 
570   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
571     const llvm::Type *EltTy = ConvertType(CTy->getElementType());
572     llvm::Value *U = llvm::UndefValue::get(EltTy);
573     return RValue::getComplex(std::make_pair(U, U));
574   }
575 
576   // If this is a use of an undefined aggregate type, the aggregate must have an
577   // identifiable address.  Just because the contents of the value are undefined
578   // doesn't mean that the address can't be taken and compared.
579   if (hasAggregateLLVMType(Ty)) {
580     llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
581     return RValue::getAggregate(DestPtr);
582   }
583 
584   return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
585 }
586 
587 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
588                                               const char *Name) {
589   ErrorUnsupported(E, Name);
590   return GetUndefRValue(E->getType());
591 }
592 
593 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
594                                               const char *Name) {
595   ErrorUnsupported(E, Name);
596   llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
597   return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType());
598 }
599 
600 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E) {
601   LValue LV = EmitLValue(E);
602   if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
603     EmitCheck(LV.getAddress(),
604               getContext().getTypeSizeInChars(E->getType()).getQuantity());
605   return LV;
606 }
607 
608 /// EmitLValue - Emit code to compute a designator that specifies the location
609 /// of the expression.
610 ///
611 /// This can return one of two things: a simple address or a bitfield reference.
612 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
613 /// an LLVM pointer type.
614 ///
615 /// If this returns a bitfield reference, nothing about the pointee type of the
616 /// LLVM value is known: For example, it may not be a pointer to an integer.
617 ///
618 /// If this returns a normal address, and if the lvalue's C type is fixed size,
619 /// this method guarantees that the returned pointer type will point to an LLVM
620 /// type of the same size of the lvalue's type.  If the lvalue has a variable
621 /// length type, this is not possible.
622 ///
623 LValue CodeGenFunction::EmitLValue(const Expr *E) {
624   switch (E->getStmtClass()) {
625   default: return EmitUnsupportedLValue(E, "l-value expression");
626 
627   case Expr::ObjCSelectorExprClass:
628   return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
629   case Expr::ObjCIsaExprClass:
630     return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
631   case Expr::BinaryOperatorClass:
632     return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
633   case Expr::CompoundAssignOperatorClass:
634     if (!E->getType()->isAnyComplexType())
635       return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
636     return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
637   case Expr::CallExprClass:
638   case Expr::CXXMemberCallExprClass:
639   case Expr::CXXOperatorCallExprClass:
640     return EmitCallExprLValue(cast<CallExpr>(E));
641   case Expr::VAArgExprClass:
642     return EmitVAArgExprLValue(cast<VAArgExpr>(E));
643   case Expr::DeclRefExprClass:
644     return EmitDeclRefLValue(cast<DeclRefExpr>(E));
645   case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
646   case Expr::GenericSelectionExprClass:
647     return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
648   case Expr::PredefinedExprClass:
649     return EmitPredefinedLValue(cast<PredefinedExpr>(E));
650   case Expr::StringLiteralClass:
651     return EmitStringLiteralLValue(cast<StringLiteral>(E));
652   case Expr::ObjCEncodeExprClass:
653     return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
654 
655   case Expr::BlockDeclRefExprClass:
656     return EmitBlockDeclRefLValue(cast<BlockDeclRefExpr>(E));
657 
658   case Expr::CXXTemporaryObjectExprClass:
659   case Expr::CXXConstructExprClass:
660     return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
661   case Expr::CXXBindTemporaryExprClass:
662     return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
663   case Expr::ExprWithCleanupsClass:
664     return EmitExprWithCleanupsLValue(cast<ExprWithCleanups>(E));
665   case Expr::CXXScalarValueInitExprClass:
666     return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E));
667   case Expr::CXXDefaultArgExprClass:
668     return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
669   case Expr::CXXTypeidExprClass:
670     return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
671 
672   case Expr::ObjCMessageExprClass:
673     return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
674   case Expr::ObjCIvarRefExprClass:
675     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
676   case Expr::ObjCPropertyRefExprClass:
677     return EmitObjCPropertyRefLValue(cast<ObjCPropertyRefExpr>(E));
678   case Expr::StmtExprClass:
679     return EmitStmtExprLValue(cast<StmtExpr>(E));
680   case Expr::UnaryOperatorClass:
681     return EmitUnaryOpLValue(cast<UnaryOperator>(E));
682   case Expr::ArraySubscriptExprClass:
683     return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
684   case Expr::ExtVectorElementExprClass:
685     return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
686   case Expr::MemberExprClass:
687     return EmitMemberExpr(cast<MemberExpr>(E));
688   case Expr::CompoundLiteralExprClass:
689     return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
690   case Expr::ConditionalOperatorClass:
691     return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
692   case Expr::BinaryConditionalOperatorClass:
693     return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
694   case Expr::ChooseExprClass:
695     return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext()));
696   case Expr::OpaqueValueExprClass:
697     return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
698   case Expr::ImplicitCastExprClass:
699   case Expr::CStyleCastExprClass:
700   case Expr::CXXFunctionalCastExprClass:
701   case Expr::CXXStaticCastExprClass:
702   case Expr::CXXDynamicCastExprClass:
703   case Expr::CXXReinterpretCastExprClass:
704   case Expr::CXXConstCastExprClass:
705   case Expr::ObjCBridgedCastExprClass:
706     return EmitCastLValue(cast<CastExpr>(E));
707 
708   case Expr::MaterializeTemporaryExprClass:
709     return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
710   }
711 }
712 
713 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue) {
714   return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
715                           lvalue.getAlignment(), lvalue.getType(),
716                           lvalue.getTBAAInfo());
717 }
718 
719 llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
720                                               unsigned Alignment, QualType Ty,
721                                               llvm::MDNode *TBAAInfo) {
722   llvm::LoadInst *Load = Builder.CreateLoad(Addr, "tmp");
723   if (Volatile)
724     Load->setVolatile(true);
725   if (Alignment)
726     Load->setAlignment(Alignment);
727   if (TBAAInfo)
728     CGM.DecorateInstruction(Load, TBAAInfo);
729 
730   return EmitFromMemory(Load, Ty);
731 }
732 
733 static bool isBooleanUnderlyingType(QualType Ty) {
734   if (const EnumType *ET = dyn_cast<EnumType>(Ty))
735     return ET->getDecl()->getIntegerType()->isBooleanType();
736   return false;
737 }
738 
739 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
740   // Bool has a different representation in memory than in registers.
741   if (Ty->isBooleanType() || isBooleanUnderlyingType(Ty)) {
742     // This should really always be an i1, but sometimes it's already
743     // an i8, and it's awkward to track those cases down.
744     if (Value->getType()->isIntegerTy(1))
745       return Builder.CreateZExt(Value, Builder.getInt8Ty(), "frombool");
746     assert(Value->getType()->isIntegerTy(8) && "value rep of bool not i1/i8");
747   }
748 
749   return Value;
750 }
751 
752 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
753   // Bool has a different representation in memory than in registers.
754   if (Ty->isBooleanType() || isBooleanUnderlyingType(Ty)) {
755     assert(Value->getType()->isIntegerTy(8) && "memory rep of bool not i8");
756     return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
757   }
758 
759   return Value;
760 }
761 
762 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
763                                         bool Volatile, unsigned Alignment,
764                                         QualType Ty,
765                                         llvm::MDNode *TBAAInfo) {
766   Value = EmitToMemory(Value, Ty);
767   llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
768   if (Alignment)
769     Store->setAlignment(Alignment);
770   if (TBAAInfo)
771     CGM.DecorateInstruction(Store, TBAAInfo);
772 }
773 
774 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue) {
775   EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
776                     lvalue.getAlignment(), lvalue.getType(),
777                     lvalue.getTBAAInfo());
778 }
779 
780 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
781 /// method emits the address of the lvalue, then loads the result as an rvalue,
782 /// returning the rvalue.
783 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV) {
784   if (LV.isObjCWeak()) {
785     // load of a __weak object.
786     llvm::Value *AddrWeakObj = LV.getAddress();
787     return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
788                                                              AddrWeakObj));
789   }
790   if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak)
791     return RValue::get(EmitARCLoadWeak(LV.getAddress()));
792 
793   if (LV.isSimple()) {
794     // Functions are l-values that don't require loading.
795     if (LV.getType()->isFunctionType())
796       return RValue::get(LV.getAddress());
797 
798     // Everything needs a load.
799     return RValue::get(EmitLoadOfScalar(LV));
800   }
801 
802   if (LV.isVectorElt()) {
803     llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(),
804                                           LV.isVolatileQualified(), "tmp");
805     return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
806                                                     "vecext"));
807   }
808 
809   // If this is a reference to a subset of the elements of a vector, either
810   // shuffle the input or extract/insert them as appropriate.
811   if (LV.isExtVectorElt())
812     return EmitLoadOfExtVectorElementLValue(LV);
813 
814   if (LV.isBitField())
815     return EmitLoadOfBitfieldLValue(LV);
816 
817   assert(LV.isPropertyRef() && "Unknown LValue type!");
818   return EmitLoadOfPropertyRefLValue(LV);
819 }
820 
821 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
822   const CGBitFieldInfo &Info = LV.getBitFieldInfo();
823 
824   // Get the output type.
825   const llvm::Type *ResLTy = ConvertType(LV.getType());
826   unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy);
827 
828   // Compute the result as an OR of all of the individual component accesses.
829   llvm::Value *Res = 0;
830   for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
831     const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
832 
833     // Get the field pointer.
834     llvm::Value *Ptr = LV.getBitFieldBaseAddr();
835 
836     // Only offset by the field index if used, so that incoming values are not
837     // required to be structures.
838     if (AI.FieldIndex)
839       Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
840 
841     // Offset by the byte offset, if used.
842     if (!AI.FieldByteOffset.isZero()) {
843       Ptr = EmitCastToVoidPtr(Ptr);
844       Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset.getQuantity(),
845                                        "bf.field.offs");
846     }
847 
848     // Cast to the access type.
849     const llvm::Type *PTy = llvm::Type::getIntNPtrTy(getLLVMContext(),
850                                                      AI.AccessWidth,
851                        CGM.getContext().getTargetAddressSpace(LV.getType()));
852     Ptr = Builder.CreateBitCast(Ptr, PTy);
853 
854     // Perform the load.
855     llvm::LoadInst *Load = Builder.CreateLoad(Ptr, LV.isVolatileQualified());
856     if (!AI.AccessAlignment.isZero())
857       Load->setAlignment(AI.AccessAlignment.getQuantity());
858 
859     // Shift out unused low bits and mask out unused high bits.
860     llvm::Value *Val = Load;
861     if (AI.FieldBitStart)
862       Val = Builder.CreateLShr(Load, AI.FieldBitStart);
863     Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(AI.AccessWidth,
864                                                             AI.TargetBitWidth),
865                             "bf.clear");
866 
867     // Extend or truncate to the target size.
868     if (AI.AccessWidth < ResSizeInBits)
869       Val = Builder.CreateZExt(Val, ResLTy);
870     else if (AI.AccessWidth > ResSizeInBits)
871       Val = Builder.CreateTrunc(Val, ResLTy);
872 
873     // Shift into place, and OR into the result.
874     if (AI.TargetBitOffset)
875       Val = Builder.CreateShl(Val, AI.TargetBitOffset);
876     Res = Res ? Builder.CreateOr(Res, Val) : Val;
877   }
878 
879   // If the bit-field is signed, perform the sign-extension.
880   //
881   // FIXME: This can easily be folded into the load of the high bits, which
882   // could also eliminate the mask of high bits in some situations.
883   if (Info.isSigned()) {
884     unsigned ExtraBits = ResSizeInBits - Info.getSize();
885     if (ExtraBits)
886       Res = Builder.CreateAShr(Builder.CreateShl(Res, ExtraBits),
887                                ExtraBits, "bf.val.sext");
888   }
889 
890   return RValue::get(Res);
891 }
892 
893 // If this is a reference to a subset of the elements of a vector, create an
894 // appropriate shufflevector.
895 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
896   llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(),
897                                         LV.isVolatileQualified(), "tmp");
898 
899   const llvm::Constant *Elts = LV.getExtVectorElts();
900 
901   // If the result of the expression is a non-vector type, we must be extracting
902   // a single element.  Just codegen as an extractelement.
903   const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
904   if (!ExprVT) {
905     unsigned InIdx = getAccessedFieldNo(0, Elts);
906     llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
907     return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
908   }
909 
910   // Always use shuffle vector to try to retain the original program structure
911   unsigned NumResultElts = ExprVT->getNumElements();
912 
913   llvm::SmallVector<llvm::Constant*, 4> Mask;
914   for (unsigned i = 0; i != NumResultElts; ++i) {
915     unsigned InIdx = getAccessedFieldNo(i, Elts);
916     Mask.push_back(llvm::ConstantInt::get(Int32Ty, InIdx));
917   }
918 
919   llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
920   Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
921                                     MaskV, "tmp");
922   return RValue::get(Vec);
923 }
924 
925 
926 
927 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
928 /// lvalue, where both are guaranteed to the have the same type, and that type
929 /// is 'Ty'.
930 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst) {
931   if (!Dst.isSimple()) {
932     if (Dst.isVectorElt()) {
933       // Read/modify/write the vector, inserting the new element.
934       llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(),
935                                             Dst.isVolatileQualified(), "tmp");
936       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
937                                         Dst.getVectorIdx(), "vecins");
938       Builder.CreateStore(Vec, Dst.getVectorAddr(),Dst.isVolatileQualified());
939       return;
940     }
941 
942     // If this is an update of extended vector elements, insert them as
943     // appropriate.
944     if (Dst.isExtVectorElt())
945       return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
946 
947     if (Dst.isBitField())
948       return EmitStoreThroughBitfieldLValue(Src, Dst);
949 
950     assert(Dst.isPropertyRef() && "Unknown LValue type");
951     return EmitStoreThroughPropertyRefLValue(Src, Dst);
952   }
953 
954   // There's special magic for assigning into an ARC-qualified l-value.
955   if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
956     switch (Lifetime) {
957     case Qualifiers::OCL_None:
958       llvm_unreachable("present but none");
959 
960     case Qualifiers::OCL_ExplicitNone:
961       // nothing special
962       break;
963 
964     case Qualifiers::OCL_Strong:
965       EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
966       return;
967 
968     case Qualifiers::OCL_Weak:
969       EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
970       return;
971 
972     case Qualifiers::OCL_Autoreleasing:
973       Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
974                                                      Src.getScalarVal()));
975       // fall into the normal path
976       break;
977     }
978   }
979 
980   if (Dst.isObjCWeak() && !Dst.isNonGC()) {
981     // load of a __weak object.
982     llvm::Value *LvalueDst = Dst.getAddress();
983     llvm::Value *src = Src.getScalarVal();
984      CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
985     return;
986   }
987 
988   if (Dst.isObjCStrong() && !Dst.isNonGC()) {
989     // load of a __strong object.
990     llvm::Value *LvalueDst = Dst.getAddress();
991     llvm::Value *src = Src.getScalarVal();
992     if (Dst.isObjCIvar()) {
993       assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
994       const llvm::Type *ResultType = ConvertType(getContext().LongTy);
995       llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
996       llvm::Value *dst = RHS;
997       RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
998       llvm::Value *LHS =
999         Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
1000       llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
1001       CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
1002                                               BytesBetween);
1003     } else if (Dst.isGlobalObjCRef()) {
1004       CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1005                                                 Dst.isThreadLocalRef());
1006     }
1007     else
1008       CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
1009     return;
1010   }
1011 
1012   assert(Src.isScalar() && "Can't emit an agg store with this method");
1013   EmitStoreOfScalar(Src.getScalarVal(), Dst);
1014 }
1015 
1016 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
1017                                                      llvm::Value **Result) {
1018   const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
1019 
1020   // Get the output type.
1021   const llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
1022   unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy);
1023 
1024   // Get the source value, truncated to the width of the bit-field.
1025   llvm::Value *SrcVal = Src.getScalarVal();
1026 
1027   if (Dst.getType()->isBooleanType())
1028     SrcVal = Builder.CreateIntCast(SrcVal, ResLTy, /*IsSigned=*/false);
1029 
1030   SrcVal = Builder.CreateAnd(SrcVal, llvm::APInt::getLowBitsSet(ResSizeInBits,
1031                                                                 Info.getSize()),
1032                              "bf.value");
1033 
1034   // Return the new value of the bit-field, if requested.
1035   if (Result) {
1036     // Cast back to the proper type for result.
1037     const llvm::Type *SrcTy = Src.getScalarVal()->getType();
1038     llvm::Value *ReloadVal = Builder.CreateIntCast(SrcVal, SrcTy, false,
1039                                                    "bf.reload.val");
1040 
1041     // Sign extend if necessary.
1042     if (Info.isSigned()) {
1043       unsigned ExtraBits = ResSizeInBits - Info.getSize();
1044       if (ExtraBits)
1045         ReloadVal = Builder.CreateAShr(Builder.CreateShl(ReloadVal, ExtraBits),
1046                                        ExtraBits, "bf.reload.sext");
1047     }
1048 
1049     *Result = ReloadVal;
1050   }
1051 
1052   // Iterate over the components, writing each piece to memory.
1053   for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
1054     const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
1055 
1056     // Get the field pointer.
1057     llvm::Value *Ptr = Dst.getBitFieldBaseAddr();
1058     unsigned addressSpace =
1059       cast<llvm::PointerType>(Ptr->getType())->getAddressSpace();
1060 
1061     // Only offset by the field index if used, so that incoming values are not
1062     // required to be structures.
1063     if (AI.FieldIndex)
1064       Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
1065 
1066     // Offset by the byte offset, if used.
1067     if (!AI.FieldByteOffset.isZero()) {
1068       Ptr = EmitCastToVoidPtr(Ptr);
1069       Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset.getQuantity(),
1070                                        "bf.field.offs");
1071     }
1072 
1073     // Cast to the access type.
1074     const llvm::Type *AccessLTy =
1075       llvm::Type::getIntNTy(getLLVMContext(), AI.AccessWidth);
1076 
1077     const llvm::Type *PTy = AccessLTy->getPointerTo(addressSpace);
1078     Ptr = Builder.CreateBitCast(Ptr, PTy);
1079 
1080     // Extract the piece of the bit-field value to write in this access, limited
1081     // to the values that are part of this access.
1082     llvm::Value *Val = SrcVal;
1083     if (AI.TargetBitOffset)
1084       Val = Builder.CreateLShr(Val, AI.TargetBitOffset);
1085     Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(ResSizeInBits,
1086                                                             AI.TargetBitWidth));
1087 
1088     // Extend or truncate to the access size.
1089     if (ResSizeInBits < AI.AccessWidth)
1090       Val = Builder.CreateZExt(Val, AccessLTy);
1091     else if (ResSizeInBits > AI.AccessWidth)
1092       Val = Builder.CreateTrunc(Val, AccessLTy);
1093 
1094     // Shift into the position in memory.
1095     if (AI.FieldBitStart)
1096       Val = Builder.CreateShl(Val, AI.FieldBitStart);
1097 
1098     // If necessary, load and OR in bits that are outside of the bit-field.
1099     if (AI.TargetBitWidth != AI.AccessWidth) {
1100       llvm::LoadInst *Load = Builder.CreateLoad(Ptr, Dst.isVolatileQualified());
1101       if (!AI.AccessAlignment.isZero())
1102         Load->setAlignment(AI.AccessAlignment.getQuantity());
1103 
1104       // Compute the mask for zeroing the bits that are part of the bit-field.
1105       llvm::APInt InvMask =
1106         ~llvm::APInt::getBitsSet(AI.AccessWidth, AI.FieldBitStart,
1107                                  AI.FieldBitStart + AI.TargetBitWidth);
1108 
1109       // Apply the mask and OR in to the value to write.
1110       Val = Builder.CreateOr(Builder.CreateAnd(Load, InvMask), Val);
1111     }
1112 
1113     // Write the value.
1114     llvm::StoreInst *Store = Builder.CreateStore(Val, Ptr,
1115                                                  Dst.isVolatileQualified());
1116     if (!AI.AccessAlignment.isZero())
1117       Store->setAlignment(AI.AccessAlignment.getQuantity());
1118   }
1119 }
1120 
1121 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
1122                                                                LValue Dst) {
1123   // This access turns into a read/modify/write of the vector.  Load the input
1124   // value now.
1125   llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(),
1126                                         Dst.isVolatileQualified(), "tmp");
1127   const llvm::Constant *Elts = Dst.getExtVectorElts();
1128 
1129   llvm::Value *SrcVal = Src.getScalarVal();
1130 
1131   if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
1132     unsigned NumSrcElts = VTy->getNumElements();
1133     unsigned NumDstElts =
1134        cast<llvm::VectorType>(Vec->getType())->getNumElements();
1135     if (NumDstElts == NumSrcElts) {
1136       // Use shuffle vector is the src and destination are the same number of
1137       // elements and restore the vector mask since it is on the side it will be
1138       // stored.
1139       llvm::SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
1140       for (unsigned i = 0; i != NumSrcElts; ++i) {
1141         unsigned InIdx = getAccessedFieldNo(i, Elts);
1142         Mask[InIdx] = llvm::ConstantInt::get(Int32Ty, i);
1143       }
1144 
1145       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1146       Vec = Builder.CreateShuffleVector(SrcVal,
1147                                         llvm::UndefValue::get(Vec->getType()),
1148                                         MaskV, "tmp");
1149     } else if (NumDstElts > NumSrcElts) {
1150       // Extended the source vector to the same length and then shuffle it
1151       // into the destination.
1152       // FIXME: since we're shuffling with undef, can we just use the indices
1153       //        into that?  This could be simpler.
1154       llvm::SmallVector<llvm::Constant*, 4> ExtMask;
1155       unsigned i;
1156       for (i = 0; i != NumSrcElts; ++i)
1157         ExtMask.push_back(llvm::ConstantInt::get(Int32Ty, i));
1158       for (; i != NumDstElts; ++i)
1159         ExtMask.push_back(llvm::UndefValue::get(Int32Ty));
1160       llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
1161       llvm::Value *ExtSrcVal =
1162         Builder.CreateShuffleVector(SrcVal,
1163                                     llvm::UndefValue::get(SrcVal->getType()),
1164                                     ExtMaskV, "tmp");
1165       // build identity
1166       llvm::SmallVector<llvm::Constant*, 4> Mask;
1167       for (unsigned i = 0; i != NumDstElts; ++i)
1168         Mask.push_back(llvm::ConstantInt::get(Int32Ty, i));
1169 
1170       // modify when what gets shuffled in
1171       for (unsigned i = 0; i != NumSrcElts; ++i) {
1172         unsigned Idx = getAccessedFieldNo(i, Elts);
1173         Mask[Idx] = llvm::ConstantInt::get(Int32Ty, i+NumDstElts);
1174       }
1175       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1176       Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV, "tmp");
1177     } else {
1178       // We should never shorten the vector
1179       assert(0 && "unexpected shorten vector length");
1180     }
1181   } else {
1182     // If the Src is a scalar (not a vector) it must be updating one element.
1183     unsigned InIdx = getAccessedFieldNo(0, Elts);
1184     llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
1185     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
1186   }
1187 
1188   Builder.CreateStore(Vec, Dst.getExtVectorAddr(), Dst.isVolatileQualified());
1189 }
1190 
1191 // setObjCGCLValueClass - sets class of he lvalue for the purpose of
1192 // generating write-barries API. It is currently a global, ivar,
1193 // or neither.
1194 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
1195                                  LValue &LV) {
1196   if (Ctx.getLangOptions().getGCMode() == LangOptions::NonGC)
1197     return;
1198 
1199   if (isa<ObjCIvarRefExpr>(E)) {
1200     LV.setObjCIvar(true);
1201     ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E));
1202     LV.setBaseIvarExp(Exp->getBase());
1203     LV.setObjCArray(E->getType()->isArrayType());
1204     return;
1205   }
1206 
1207   if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) {
1208     if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
1209       if (VD->hasGlobalStorage()) {
1210         LV.setGlobalObjCRef(true);
1211         LV.setThreadLocalRef(VD->isThreadSpecified());
1212       }
1213     }
1214     LV.setObjCArray(E->getType()->isArrayType());
1215     return;
1216   }
1217 
1218   if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) {
1219     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1220     return;
1221   }
1222 
1223   if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) {
1224     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1225     if (LV.isObjCIvar()) {
1226       // If cast is to a structure pointer, follow gcc's behavior and make it
1227       // a non-ivar write-barrier.
1228       QualType ExpTy = E->getType();
1229       if (ExpTy->isPointerType())
1230         ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1231       if (ExpTy->isRecordType())
1232         LV.setObjCIvar(false);
1233     }
1234     return;
1235   }
1236 
1237   if (const GenericSelectionExpr *Exp = dyn_cast<GenericSelectionExpr>(E)) {
1238     setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1239     return;
1240   }
1241 
1242   if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) {
1243     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1244     return;
1245   }
1246 
1247   if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) {
1248     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1249     return;
1250   }
1251 
1252   if (const ObjCBridgedCastExpr *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
1253     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1254     return;
1255   }
1256 
1257   if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
1258     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1259     if (LV.isObjCIvar() && !LV.isObjCArray())
1260       // Using array syntax to assigning to what an ivar points to is not
1261       // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
1262       LV.setObjCIvar(false);
1263     else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1264       // Using array syntax to assigning to what global points to is not
1265       // same as assigning to the global itself. {id *G;} G[i] = 0;
1266       LV.setGlobalObjCRef(false);
1267     return;
1268   }
1269 
1270   if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) {
1271     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1272     // We don't know if member is an 'ivar', but this flag is looked at
1273     // only in the context of LV.isObjCIvar().
1274     LV.setObjCArray(E->getType()->isArrayType());
1275     return;
1276   }
1277 }
1278 
1279 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1280                                       const Expr *E, const VarDecl *VD) {
1281   assert((VD->hasExternalStorage() || VD->isFileVarDecl()) &&
1282          "Var decl must have external storage or be a file var decl!");
1283 
1284   llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
1285   if (VD->getType()->isReferenceType())
1286     V = CGF.Builder.CreateLoad(V, "tmp");
1287   unsigned Alignment = CGF.getContext().getDeclAlign(VD).getQuantity();
1288   LValue LV = CGF.MakeAddrLValue(V, E->getType(), Alignment);
1289   setObjCGCLValueClass(CGF.getContext(), E, LV);
1290   return LV;
1291 }
1292 
1293 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
1294                                       const Expr *E, const FunctionDecl *FD) {
1295   llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
1296   if (!FD->hasPrototype()) {
1297     if (const FunctionProtoType *Proto =
1298             FD->getType()->getAs<FunctionProtoType>()) {
1299       // Ugly case: for a K&R-style definition, the type of the definition
1300       // isn't the same as the type of a use.  Correct for this with a
1301       // bitcast.
1302       QualType NoProtoType =
1303           CGF.getContext().getFunctionNoProtoType(Proto->getResultType());
1304       NoProtoType = CGF.getContext().getPointerType(NoProtoType);
1305       V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType), "tmp");
1306     }
1307   }
1308   unsigned Alignment = CGF.getContext().getDeclAlign(FD).getQuantity();
1309   return CGF.MakeAddrLValue(V, E->getType(), Alignment);
1310 }
1311 
1312 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
1313   const NamedDecl *ND = E->getDecl();
1314   unsigned Alignment = getContext().getDeclAlign(ND).getQuantity();
1315 
1316   if (ND->hasAttr<WeakRefAttr>()) {
1317     const ValueDecl *VD = cast<ValueDecl>(ND);
1318     llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
1319     return MakeAddrLValue(Aliasee, E->getType(), Alignment);
1320   }
1321 
1322   if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1323 
1324     // Check if this is a global variable.
1325     if (VD->hasExternalStorage() || VD->isFileVarDecl())
1326       return EmitGlobalVarDeclLValue(*this, E, VD);
1327 
1328     bool NonGCable = VD->hasLocalStorage() &&
1329                      !VD->getType()->isReferenceType() &&
1330                      !VD->hasAttr<BlocksAttr>();
1331 
1332     llvm::Value *V = LocalDeclMap[VD];
1333     if (!V && VD->isStaticLocal())
1334       V = CGM.getStaticLocalDeclAddress(VD);
1335     assert(V && "DeclRefExpr not entered in LocalDeclMap?");
1336 
1337     if (VD->hasAttr<BlocksAttr>())
1338       V = BuildBlockByrefAddress(V, VD);
1339 
1340     if (VD->getType()->isReferenceType())
1341       V = Builder.CreateLoad(V, "tmp");
1342 
1343     LValue LV = MakeAddrLValue(V, E->getType(), Alignment);
1344     if (NonGCable) {
1345       LV.getQuals().removeObjCGCAttr();
1346       LV.setNonGC(true);
1347     }
1348     setObjCGCLValueClass(getContext(), E, LV);
1349     return LV;
1350   }
1351 
1352   if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND))
1353     return EmitFunctionDeclLValue(*this, E, fn);
1354 
1355   assert(false && "Unhandled DeclRefExpr");
1356 
1357   // an invalid LValue, but the assert will
1358   // ensure that this point is never reached.
1359   return LValue();
1360 }
1361 
1362 LValue CodeGenFunction::EmitBlockDeclRefLValue(const BlockDeclRefExpr *E) {
1363   unsigned Alignment =
1364     getContext().getDeclAlign(E->getDecl()).getQuantity();
1365   return MakeAddrLValue(GetAddrOfBlockDecl(E), E->getType(), Alignment);
1366 }
1367 
1368 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
1369   // __extension__ doesn't affect lvalue-ness.
1370   if (E->getOpcode() == UO_Extension)
1371     return EmitLValue(E->getSubExpr());
1372 
1373   QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
1374   switch (E->getOpcode()) {
1375   default: assert(0 && "Unknown unary operator lvalue!");
1376   case UO_Deref: {
1377     QualType T = E->getSubExpr()->getType()->getPointeeType();
1378     assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
1379 
1380     LValue LV = MakeAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
1381     LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
1382 
1383     // We should not generate __weak write barrier on indirect reference
1384     // of a pointer to object; as in void foo (__weak id *param); *param = 0;
1385     // But, we continue to generate __strong write barrier on indirect write
1386     // into a pointer to object.
1387     if (getContext().getLangOptions().ObjC1 &&
1388         getContext().getLangOptions().getGCMode() != LangOptions::NonGC &&
1389         LV.isObjCWeak())
1390       LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
1391     return LV;
1392   }
1393   case UO_Real:
1394   case UO_Imag: {
1395     LValue LV = EmitLValue(E->getSubExpr());
1396     assert(LV.isSimple() && "real/imag on non-ordinary l-value");
1397     llvm::Value *Addr = LV.getAddress();
1398 
1399     // real and imag are valid on scalars.  This is a faster way of
1400     // testing that.
1401     if (!cast<llvm::PointerType>(Addr->getType())
1402            ->getElementType()->isStructTy()) {
1403       assert(E->getSubExpr()->getType()->isArithmeticType());
1404       return LV;
1405     }
1406 
1407     assert(E->getSubExpr()->getType()->isAnyComplexType());
1408 
1409     unsigned Idx = E->getOpcode() == UO_Imag;
1410     return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(),
1411                                                   Idx, "idx"),
1412                           ExprTy);
1413   }
1414   case UO_PreInc:
1415   case UO_PreDec: {
1416     LValue LV = EmitLValue(E->getSubExpr());
1417     bool isInc = E->getOpcode() == UO_PreInc;
1418 
1419     if (E->getType()->isAnyComplexType())
1420       EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
1421     else
1422       EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
1423     return LV;
1424   }
1425   }
1426 }
1427 
1428 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
1429   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
1430                         E->getType());
1431 }
1432 
1433 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
1434   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
1435                         E->getType());
1436 }
1437 
1438 
1439 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
1440   switch (E->getIdentType()) {
1441   default:
1442     return EmitUnsupportedLValue(E, "predefined expression");
1443 
1444   case PredefinedExpr::Func:
1445   case PredefinedExpr::Function:
1446   case PredefinedExpr::PrettyFunction: {
1447     unsigned Type = E->getIdentType();
1448     std::string GlobalVarName;
1449 
1450     switch (Type) {
1451     default: assert(0 && "Invalid type");
1452     case PredefinedExpr::Func:
1453       GlobalVarName = "__func__.";
1454       break;
1455     case PredefinedExpr::Function:
1456       GlobalVarName = "__FUNCTION__.";
1457       break;
1458     case PredefinedExpr::PrettyFunction:
1459       GlobalVarName = "__PRETTY_FUNCTION__.";
1460       break;
1461     }
1462 
1463     llvm::StringRef FnName = CurFn->getName();
1464     if (FnName.startswith("\01"))
1465       FnName = FnName.substr(1);
1466     GlobalVarName += FnName;
1467 
1468     const Decl *CurDecl = CurCodeDecl;
1469     if (CurDecl == 0)
1470       CurDecl = getContext().getTranslationUnitDecl();
1471 
1472     std::string FunctionName =
1473         (isa<BlockDecl>(CurDecl)
1474          ? FnName.str()
1475          : PredefinedExpr::ComputeName((PredefinedExpr::IdentType)Type, CurDecl));
1476 
1477     llvm::Constant *C =
1478       CGM.GetAddrOfConstantCString(FunctionName, GlobalVarName.c_str());
1479     return MakeAddrLValue(C, E->getType());
1480   }
1481   }
1482 }
1483 
1484 llvm::BasicBlock *CodeGenFunction::getTrapBB() {
1485   const CodeGenOptions &GCO = CGM.getCodeGenOpts();
1486 
1487   // If we are not optimzing, don't collapse all calls to trap in the function
1488   // to the same call, that way, in the debugger they can see which operation
1489   // did in fact fail.  If we are optimizing, we collapse all calls to trap down
1490   // to just one per function to save on codesize.
1491   if (GCO.OptimizationLevel && TrapBB)
1492     return TrapBB;
1493 
1494   llvm::BasicBlock *Cont = 0;
1495   if (HaveInsertPoint()) {
1496     Cont = createBasicBlock("cont");
1497     EmitBranch(Cont);
1498   }
1499   TrapBB = createBasicBlock("trap");
1500   EmitBlock(TrapBB);
1501 
1502   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap, 0, 0);
1503   llvm::CallInst *TrapCall = Builder.CreateCall(F);
1504   TrapCall->setDoesNotReturn();
1505   TrapCall->setDoesNotThrow();
1506   Builder.CreateUnreachable();
1507 
1508   if (Cont)
1509     EmitBlock(Cont);
1510   return TrapBB;
1511 }
1512 
1513 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
1514 /// array to pointer, return the array subexpression.
1515 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
1516   // If this isn't just an array->pointer decay, bail out.
1517   const CastExpr *CE = dyn_cast<CastExpr>(E);
1518   if (CE == 0 || CE->getCastKind() != CK_ArrayToPointerDecay)
1519     return 0;
1520 
1521   // If this is a decay from variable width array, bail out.
1522   const Expr *SubExpr = CE->getSubExpr();
1523   if (SubExpr->getType()->isVariableArrayType())
1524     return 0;
1525 
1526   return SubExpr;
1527 }
1528 
1529 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
1530   // The index must always be an integer, which is not an aggregate.  Emit it.
1531   llvm::Value *Idx = EmitScalarExpr(E->getIdx());
1532   QualType IdxTy  = E->getIdx()->getType();
1533   bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
1534 
1535   // If the base is a vector type, then we are forming a vector element lvalue
1536   // with this subscript.
1537   if (E->getBase()->getType()->isVectorType()) {
1538     // Emit the vector as an lvalue to get its address.
1539     LValue LHS = EmitLValue(E->getBase());
1540     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
1541     Idx = Builder.CreateIntCast(Idx, Int32Ty, IdxSigned, "vidx");
1542     return LValue::MakeVectorElt(LHS.getAddress(), Idx,
1543                                  E->getBase()->getType());
1544   }
1545 
1546   // Extend or truncate the index type to 32 or 64-bits.
1547   if (Idx->getType() != IntPtrTy)
1548     Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
1549 
1550   // FIXME: As llvm implements the object size checking, this can come out.
1551   if (CatchUndefined) {
1552     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E->getBase())){
1553       if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1554         if (ICE->getCastKind() == CK_ArrayToPointerDecay) {
1555           if (const ConstantArrayType *CAT
1556               = getContext().getAsConstantArrayType(DRE->getType())) {
1557             llvm::APInt Size = CAT->getSize();
1558             llvm::BasicBlock *Cont = createBasicBlock("cont");
1559             Builder.CreateCondBr(Builder.CreateICmpULE(Idx,
1560                                   llvm::ConstantInt::get(Idx->getType(), Size)),
1561                                  Cont, getTrapBB());
1562             EmitBlock(Cont);
1563           }
1564         }
1565       }
1566     }
1567   }
1568 
1569   // We know that the pointer points to a type of the correct size, unless the
1570   // size is a VLA or Objective-C interface.
1571   llvm::Value *Address = 0;
1572   unsigned ArrayAlignment = 0;
1573   if (const VariableArrayType *vla =
1574         getContext().getAsVariableArrayType(E->getType())) {
1575     // The base must be a pointer, which is not an aggregate.  Emit
1576     // it.  It needs to be emitted first in case it's what captures
1577     // the VLA bounds.
1578     Address = EmitScalarExpr(E->getBase());
1579 
1580     // The element count here is the total number of non-VLA elements.
1581     llvm::Value *numElements = getVLASize(vla).first;
1582 
1583     // Effectively, the multiply by the VLA size is part of the GEP.
1584     // GEP indexes are signed, and scaling an index isn't permitted to
1585     // signed-overflow, so we use the same semantics for our explicit
1586     // multiply.  We suppress this if overflow is not undefined behavior.
1587     if (getLangOptions().isSignedOverflowDefined()) {
1588       Idx = Builder.CreateMul(Idx, numElements);
1589       Address = Builder.CreateGEP(Address, Idx, "arrayidx");
1590     } else {
1591       Idx = Builder.CreateNSWMul(Idx, numElements);
1592       Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
1593     }
1594   } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
1595     // Indexing over an interface, as in "NSString *P; P[4];"
1596     llvm::Value *InterfaceSize =
1597       llvm::ConstantInt::get(Idx->getType(),
1598           getContext().getTypeSizeInChars(OIT).getQuantity());
1599 
1600     Idx = Builder.CreateMul(Idx, InterfaceSize);
1601 
1602     // The base must be a pointer, which is not an aggregate.  Emit it.
1603     llvm::Value *Base = EmitScalarExpr(E->getBase());
1604     Address = EmitCastToVoidPtr(Base);
1605     Address = Builder.CreateGEP(Address, Idx, "arrayidx");
1606     Address = Builder.CreateBitCast(Address, Base->getType());
1607   } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
1608     // If this is A[i] where A is an array, the frontend will have decayed the
1609     // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
1610     // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
1611     // "gep x, i" here.  Emit one "gep A, 0, i".
1612     assert(Array->getType()->isArrayType() &&
1613            "Array to pointer decay must have array source type!");
1614     LValue ArrayLV = EmitLValue(Array);
1615     llvm::Value *ArrayPtr = ArrayLV.getAddress();
1616     llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
1617     llvm::Value *Args[] = { Zero, Idx };
1618 
1619     // Propagate the alignment from the array itself to the result.
1620     ArrayAlignment = ArrayLV.getAlignment();
1621 
1622     if (getContext().getLangOptions().isSignedOverflowDefined())
1623       Address = Builder.CreateGEP(ArrayPtr, Args, Args+2, "arrayidx");
1624     else
1625       Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, Args+2, "arrayidx");
1626   } else {
1627     // The base must be a pointer, which is not an aggregate.  Emit it.
1628     llvm::Value *Base = EmitScalarExpr(E->getBase());
1629     if (getContext().getLangOptions().isSignedOverflowDefined())
1630       Address = Builder.CreateGEP(Base, Idx, "arrayidx");
1631     else
1632       Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
1633   }
1634 
1635   QualType T = E->getBase()->getType()->getPointeeType();
1636   assert(!T.isNull() &&
1637          "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
1638 
1639   // Limit the alignment to that of the result type.
1640   if (ArrayAlignment) {
1641     unsigned Align = getContext().getTypeAlignInChars(T).getQuantity();
1642     ArrayAlignment = std::min(Align, ArrayAlignment);
1643   }
1644 
1645   LValue LV = MakeAddrLValue(Address, T, ArrayAlignment);
1646   LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
1647 
1648   if (getContext().getLangOptions().ObjC1 &&
1649       getContext().getLangOptions().getGCMode() != LangOptions::NonGC) {
1650     LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
1651     setObjCGCLValueClass(getContext(), E, LV);
1652   }
1653   return LV;
1654 }
1655 
1656 static
1657 llvm::Constant *GenerateConstantVector(llvm::LLVMContext &VMContext,
1658                                        llvm::SmallVector<unsigned, 4> &Elts) {
1659   llvm::SmallVector<llvm::Constant*, 4> CElts;
1660 
1661   const llvm::Type *Int32Ty = llvm::Type::getInt32Ty(VMContext);
1662   for (unsigned i = 0, e = Elts.size(); i != e; ++i)
1663     CElts.push_back(llvm::ConstantInt::get(Int32Ty, Elts[i]));
1664 
1665   return llvm::ConstantVector::get(CElts);
1666 }
1667 
1668 LValue CodeGenFunction::
1669 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
1670   // Emit the base vector as an l-value.
1671   LValue Base;
1672 
1673   // ExtVectorElementExpr's base can either be a vector or pointer to vector.
1674   if (E->isArrow()) {
1675     // If it is a pointer to a vector, emit the address and form an lvalue with
1676     // it.
1677     llvm::Value *Ptr = EmitScalarExpr(E->getBase());
1678     const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
1679     Base = MakeAddrLValue(Ptr, PT->getPointeeType());
1680     Base.getQuals().removeObjCGCAttr();
1681   } else if (E->getBase()->isGLValue()) {
1682     // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
1683     // emit the base as an lvalue.
1684     assert(E->getBase()->getType()->isVectorType());
1685     Base = EmitLValue(E->getBase());
1686   } else {
1687     // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
1688     assert(E->getBase()->getType()->isVectorType() &&
1689            "Result must be a vector");
1690     llvm::Value *Vec = EmitScalarExpr(E->getBase());
1691 
1692     // Store the vector to memory (because LValue wants an address).
1693     llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
1694     Builder.CreateStore(Vec, VecMem);
1695     Base = MakeAddrLValue(VecMem, E->getBase()->getType());
1696   }
1697 
1698   QualType type =
1699     E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
1700 
1701   // Encode the element access list into a vector of unsigned indices.
1702   llvm::SmallVector<unsigned, 4> Indices;
1703   E->getEncodedElementAccess(Indices);
1704 
1705   if (Base.isSimple()) {
1706     llvm::Constant *CV = GenerateConstantVector(getLLVMContext(), Indices);
1707     return LValue::MakeExtVectorElt(Base.getAddress(), CV, type);
1708   }
1709   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
1710 
1711   llvm::Constant *BaseElts = Base.getExtVectorElts();
1712   llvm::SmallVector<llvm::Constant *, 4> CElts;
1713 
1714   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1715     if (isa<llvm::ConstantAggregateZero>(BaseElts))
1716       CElts.push_back(llvm::ConstantInt::get(Int32Ty, 0));
1717     else
1718       CElts.push_back(cast<llvm::Constant>(BaseElts->getOperand(Indices[i])));
1719   }
1720   llvm::Constant *CV = llvm::ConstantVector::get(CElts);
1721   return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type);
1722 }
1723 
1724 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
1725   bool isNonGC = false;
1726   Expr *BaseExpr = E->getBase();
1727   llvm::Value *BaseValue = NULL;
1728   Qualifiers BaseQuals;
1729 
1730   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
1731   if (E->isArrow()) {
1732     BaseValue = EmitScalarExpr(BaseExpr);
1733     const PointerType *PTy =
1734       BaseExpr->getType()->getAs<PointerType>();
1735     BaseQuals = PTy->getPointeeType().getQualifiers();
1736   } else {
1737     LValue BaseLV = EmitLValue(BaseExpr);
1738     if (BaseLV.isNonGC())
1739       isNonGC = true;
1740     // FIXME: this isn't right for bitfields.
1741     BaseValue = BaseLV.getAddress();
1742     QualType BaseTy = BaseExpr->getType();
1743     BaseQuals = BaseTy.getQualifiers();
1744   }
1745 
1746   NamedDecl *ND = E->getMemberDecl();
1747   if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) {
1748     LValue LV = EmitLValueForField(BaseValue, Field,
1749                                    BaseQuals.getCVRQualifiers());
1750     LV.setNonGC(isNonGC);
1751     setObjCGCLValueClass(getContext(), E, LV);
1752     return LV;
1753   }
1754 
1755   if (VarDecl *VD = dyn_cast<VarDecl>(ND))
1756     return EmitGlobalVarDeclLValue(*this, E, VD);
1757 
1758   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
1759     return EmitFunctionDeclLValue(*this, E, FD);
1760 
1761   assert(false && "Unhandled member declaration!");
1762   return LValue();
1763 }
1764 
1765 LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value *BaseValue,
1766                                               const FieldDecl *Field,
1767                                               unsigned CVRQualifiers) {
1768   const CGRecordLayout &RL =
1769     CGM.getTypes().getCGRecordLayout(Field->getParent());
1770   const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field);
1771   return LValue::MakeBitfield(BaseValue, Info,
1772                           Field->getType().withCVRQualifiers(CVRQualifiers));
1773 }
1774 
1775 /// EmitLValueForAnonRecordField - Given that the field is a member of
1776 /// an anonymous struct or union buried inside a record, and given
1777 /// that the base value is a pointer to the enclosing record, derive
1778 /// an lvalue for the ultimate field.
1779 LValue CodeGenFunction::EmitLValueForAnonRecordField(llvm::Value *BaseValue,
1780                                              const IndirectFieldDecl *Field,
1781                                                      unsigned CVRQualifiers) {
1782   IndirectFieldDecl::chain_iterator I = Field->chain_begin(),
1783     IEnd = Field->chain_end();
1784   while (true) {
1785     LValue LV = EmitLValueForField(BaseValue, cast<FieldDecl>(*I),
1786                                    CVRQualifiers);
1787     if (++I == IEnd) return LV;
1788 
1789     assert(LV.isSimple());
1790     BaseValue = LV.getAddress();
1791     CVRQualifiers |= LV.getVRQualifiers();
1792   }
1793 }
1794 
1795 LValue CodeGenFunction::EmitLValueForField(llvm::Value *baseAddr,
1796                                            const FieldDecl *field,
1797                                            unsigned cvr) {
1798   if (field->isBitField())
1799     return EmitLValueForBitfield(baseAddr, field, cvr);
1800 
1801   const RecordDecl *rec = field->getParent();
1802   QualType type = field->getType();
1803 
1804   bool mayAlias = rec->hasAttr<MayAliasAttr>();
1805 
1806   llvm::Value *addr;
1807   if (rec->isUnion()) {
1808     // For unions, we just cast to the appropriate type.
1809     assert(!type->isReferenceType() && "union has reference member");
1810 
1811     const llvm::Type *llvmType = CGM.getTypes().ConvertTypeForMem(type);
1812     unsigned AS =
1813       cast<llvm::PointerType>(baseAddr->getType())->getAddressSpace();
1814     addr = Builder.CreateBitCast(baseAddr, llvmType->getPointerTo(AS),
1815                                  field->getName());
1816   } else {
1817     // For structs, we GEP to the field that the record layout suggests.
1818     unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
1819     addr = Builder.CreateStructGEP(baseAddr, idx, field->getName());
1820 
1821     // If this is a reference field, load the reference right now.
1822     if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
1823       llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
1824       if (cvr & Qualifiers::Volatile) load->setVolatile(true);
1825 
1826       if (CGM.shouldUseTBAA()) {
1827         llvm::MDNode *tbaa;
1828         if (mayAlias)
1829           tbaa = CGM.getTBAAInfo(getContext().CharTy);
1830         else
1831           tbaa = CGM.getTBAAInfo(type);
1832         CGM.DecorateInstruction(load, tbaa);
1833       }
1834 
1835       addr = load;
1836       mayAlias = false;
1837       type = refType->getPointeeType();
1838       cvr = 0; // qualifiers don't recursively apply to referencee
1839     }
1840   }
1841 
1842   unsigned alignment = getContext().getDeclAlign(field).getQuantity();
1843   LValue LV = MakeAddrLValue(addr, type, alignment);
1844   LV.getQuals().addCVRQualifiers(cvr);
1845 
1846   // __weak attribute on a field is ignored.
1847   if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
1848     LV.getQuals().removeObjCGCAttr();
1849 
1850   // Fields of may_alias structs act like 'char' for TBAA purposes.
1851   // FIXME: this should get propagated down through anonymous structs
1852   // and unions.
1853   if (mayAlias && LV.getTBAAInfo())
1854     LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
1855 
1856   return LV;
1857 }
1858 
1859 LValue
1860 CodeGenFunction::EmitLValueForFieldInitialization(llvm::Value *BaseValue,
1861                                                   const FieldDecl *Field,
1862                                                   unsigned CVRQualifiers) {
1863   QualType FieldType = Field->getType();
1864 
1865   if (!FieldType->isReferenceType())
1866     return EmitLValueForField(BaseValue, Field, CVRQualifiers);
1867 
1868   const CGRecordLayout &RL =
1869     CGM.getTypes().getCGRecordLayout(Field->getParent());
1870   unsigned idx = RL.getLLVMFieldNo(Field);
1871   llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp");
1872 
1873   assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
1874 
1875   unsigned Alignment = getContext().getDeclAlign(Field).getQuantity();
1876   return MakeAddrLValue(V, FieldType, Alignment);
1877 }
1878 
1879 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
1880   llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
1881   const Expr *InitExpr = E->getInitializer();
1882   LValue Result = MakeAddrLValue(DeclPtr, E->getType());
1883 
1884   EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
1885                    /*Init*/ true);
1886 
1887   return Result;
1888 }
1889 
1890 LValue CodeGenFunction::
1891 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
1892   if (!expr->isGLValue()) {
1893     // ?: here should be an aggregate.
1894     assert((hasAggregateLLVMType(expr->getType()) &&
1895             !expr->getType()->isAnyComplexType()) &&
1896            "Unexpected conditional operator!");
1897     return EmitAggExprToLValue(expr);
1898   }
1899 
1900   const Expr *condExpr = expr->getCond();
1901   bool CondExprBool;
1902   if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
1903     const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
1904     if (!CondExprBool) std::swap(live, dead);
1905 
1906     if (!ContainsLabel(dead))
1907       return EmitLValue(live);
1908   }
1909 
1910   OpaqueValueMapping binding(*this, expr);
1911 
1912   llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
1913   llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
1914   llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
1915 
1916   ConditionalEvaluation eval(*this);
1917   EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock);
1918 
1919   // Any temporaries created here are conditional.
1920   EmitBlock(lhsBlock);
1921   eval.begin(*this);
1922   LValue lhs = EmitLValue(expr->getTrueExpr());
1923   eval.end(*this);
1924 
1925   if (!lhs.isSimple())
1926     return EmitUnsupportedLValue(expr, "conditional operator");
1927 
1928   lhsBlock = Builder.GetInsertBlock();
1929   Builder.CreateBr(contBlock);
1930 
1931   // Any temporaries created here are conditional.
1932   EmitBlock(rhsBlock);
1933   eval.begin(*this);
1934   LValue rhs = EmitLValue(expr->getFalseExpr());
1935   eval.end(*this);
1936   if (!rhs.isSimple())
1937     return EmitUnsupportedLValue(expr, "conditional operator");
1938   rhsBlock = Builder.GetInsertBlock();
1939 
1940   EmitBlock(contBlock);
1941 
1942   llvm::PHINode *phi = Builder.CreatePHI(lhs.getAddress()->getType(), 2,
1943                                          "cond-lvalue");
1944   phi->addIncoming(lhs.getAddress(), lhsBlock);
1945   phi->addIncoming(rhs.getAddress(), rhsBlock);
1946   return MakeAddrLValue(phi, expr->getType());
1947 }
1948 
1949 /// EmitCastLValue - Casts are never lvalues unless that cast is a dynamic_cast.
1950 /// If the cast is a dynamic_cast, we can have the usual lvalue result,
1951 /// otherwise if a cast is needed by the code generator in an lvalue context,
1952 /// then it must mean that we need the address of an aggregate in order to
1953 /// access one of its fields.  This can happen for all the reasons that casts
1954 /// are permitted with aggregate result, including noop aggregate casts, and
1955 /// cast from scalar to union.
1956 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
1957   switch (E->getCastKind()) {
1958   case CK_ToVoid:
1959     return EmitUnsupportedLValue(E, "unexpected cast lvalue");
1960 
1961   case CK_Dependent:
1962     llvm_unreachable("dependent cast kind in IR gen!");
1963 
1964   case CK_GetObjCProperty: {
1965     LValue LV = EmitLValue(E->getSubExpr());
1966     assert(LV.isPropertyRef());
1967     RValue RV = EmitLoadOfPropertyRefLValue(LV);
1968 
1969     // Property is an aggregate r-value.
1970     if (RV.isAggregate()) {
1971       return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
1972     }
1973 
1974     // Implicit property returns an l-value.
1975     assert(RV.isScalar());
1976     return MakeAddrLValue(RV.getScalarVal(), E->getSubExpr()->getType());
1977   }
1978 
1979   case CK_NoOp:
1980   case CK_LValueToRValue:
1981     if (!E->getSubExpr()->Classify(getContext()).isPRValue()
1982         || E->getType()->isRecordType())
1983       return EmitLValue(E->getSubExpr());
1984     // Fall through to synthesize a temporary.
1985 
1986   case CK_BitCast:
1987   case CK_ArrayToPointerDecay:
1988   case CK_FunctionToPointerDecay:
1989   case CK_NullToMemberPointer:
1990   case CK_NullToPointer:
1991   case CK_IntegralToPointer:
1992   case CK_PointerToIntegral:
1993   case CK_PointerToBoolean:
1994   case CK_VectorSplat:
1995   case CK_IntegralCast:
1996   case CK_IntegralToBoolean:
1997   case CK_IntegralToFloating:
1998   case CK_FloatingToIntegral:
1999   case CK_FloatingToBoolean:
2000   case CK_FloatingCast:
2001   case CK_FloatingRealToComplex:
2002   case CK_FloatingComplexToReal:
2003   case CK_FloatingComplexToBoolean:
2004   case CK_FloatingComplexCast:
2005   case CK_FloatingComplexToIntegralComplex:
2006   case CK_IntegralRealToComplex:
2007   case CK_IntegralComplexToReal:
2008   case CK_IntegralComplexToBoolean:
2009   case CK_IntegralComplexCast:
2010   case CK_IntegralComplexToFloatingComplex:
2011   case CK_DerivedToBaseMemberPointer:
2012   case CK_BaseToDerivedMemberPointer:
2013   case CK_MemberPointerToBoolean:
2014   case CK_AnyPointerToBlockPointerCast:
2015   case CK_ObjCProduceObject:
2016   case CK_ObjCConsumeObject: {
2017     // These casts only produce lvalues when we're binding a reference to a
2018     // temporary realized from a (converted) pure rvalue. Emit the expression
2019     // as a value, copy it into a temporary, and return an lvalue referring to
2020     // that temporary.
2021     llvm::Value *V = CreateMemTemp(E->getType(), "ref.temp");
2022     EmitAnyExprToMem(E, V, E->getType().getQualifiers(), false);
2023     return MakeAddrLValue(V, E->getType());
2024   }
2025 
2026   case CK_Dynamic: {
2027     LValue LV = EmitLValue(E->getSubExpr());
2028     llvm::Value *V = LV.getAddress();
2029     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E);
2030     return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
2031   }
2032 
2033   case CK_ConstructorConversion:
2034   case CK_UserDefinedConversion:
2035   case CK_AnyPointerToObjCPointerCast:
2036     return EmitLValue(E->getSubExpr());
2037 
2038   case CK_UncheckedDerivedToBase:
2039   case CK_DerivedToBase: {
2040     const RecordType *DerivedClassTy =
2041       E->getSubExpr()->getType()->getAs<RecordType>();
2042     CXXRecordDecl *DerivedClassDecl =
2043       cast<CXXRecordDecl>(DerivedClassTy->getDecl());
2044 
2045     LValue LV = EmitLValue(E->getSubExpr());
2046     llvm::Value *This = LV.getAddress();
2047 
2048     // Perform the derived-to-base conversion
2049     llvm::Value *Base =
2050       GetAddressOfBaseClass(This, DerivedClassDecl,
2051                             E->path_begin(), E->path_end(),
2052                             /*NullCheckValue=*/false);
2053 
2054     return MakeAddrLValue(Base, E->getType());
2055   }
2056   case CK_ToUnion:
2057     return EmitAggExprToLValue(E);
2058   case CK_BaseToDerived: {
2059     const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
2060     CXXRecordDecl *DerivedClassDecl =
2061       cast<CXXRecordDecl>(DerivedClassTy->getDecl());
2062 
2063     LValue LV = EmitLValue(E->getSubExpr());
2064 
2065     // Perform the base-to-derived conversion
2066     llvm::Value *Derived =
2067       GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
2068                                E->path_begin(), E->path_end(),
2069                                /*NullCheckValue=*/false);
2070 
2071     return MakeAddrLValue(Derived, E->getType());
2072   }
2073   case CK_LValueBitCast: {
2074     // This must be a reinterpret_cast (or c-style equivalent).
2075     const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E);
2076 
2077     LValue LV = EmitLValue(E->getSubExpr());
2078     llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2079                                            ConvertType(CE->getTypeAsWritten()));
2080     return MakeAddrLValue(V, E->getType());
2081   }
2082   case CK_ObjCObjectLValueCast: {
2083     LValue LV = EmitLValue(E->getSubExpr());
2084     QualType ToType = getContext().getLValueReferenceType(E->getType());
2085     llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2086                                            ConvertType(ToType));
2087     return MakeAddrLValue(V, E->getType());
2088   }
2089   }
2090 
2091   llvm_unreachable("Unhandled lvalue cast kind?");
2092 }
2093 
2094 LValue CodeGenFunction::EmitNullInitializationLValue(
2095                                               const CXXScalarValueInitExpr *E) {
2096   QualType Ty = E->getType();
2097   LValue LV = MakeAddrLValue(CreateMemTemp(Ty), Ty);
2098   EmitNullInitialization(LV.getAddress(), Ty);
2099   return LV;
2100 }
2101 
2102 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
2103   assert(e->isGLValue() || e->getType()->isRecordType());
2104   return getOpaqueLValueMapping(e);
2105 }
2106 
2107 LValue CodeGenFunction::EmitMaterializeTemporaryExpr(
2108                                            const MaterializeTemporaryExpr *E) {
2109   RValue RV = EmitReferenceBindingToExpr(E->GetTemporaryExpr(),
2110                                          /*InitializedDecl=*/0);
2111   return MakeAddrLValue(RV.getScalarVal(), E->getType());
2112 }
2113 
2114 
2115 //===--------------------------------------------------------------------===//
2116 //                             Expression Emission
2117 //===--------------------------------------------------------------------===//
2118 
2119 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
2120                                      ReturnValueSlot ReturnValue) {
2121   if (CGDebugInfo *DI = getDebugInfo()) {
2122     DI->setLocation(E->getLocStart());
2123     DI->UpdateLineDirectiveRegion(Builder);
2124     DI->EmitStopPoint(Builder);
2125   }
2126 
2127   // Builtins never have block type.
2128   if (E->getCallee()->getType()->isBlockPointerType())
2129     return EmitBlockCallExpr(E, ReturnValue);
2130 
2131   if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E))
2132     return EmitCXXMemberCallExpr(CE, ReturnValue);
2133 
2134   const Decl *TargetDecl = 0;
2135   if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E->getCallee())) {
2136     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
2137       TargetDecl = DRE->getDecl();
2138       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(TargetDecl))
2139         if (unsigned builtinID = FD->getBuiltinID())
2140           return EmitBuiltinExpr(FD, builtinID, E);
2141     }
2142   }
2143 
2144   if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E))
2145     if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
2146       return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
2147 
2148   if (const CXXPseudoDestructorExpr *PseudoDtor
2149           = dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
2150     QualType DestroyedType = PseudoDtor->getDestroyedType();
2151     if (getContext().getLangOptions().ObjCAutoRefCount &&
2152         DestroyedType->isObjCLifetimeType() &&
2153         (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
2154          DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
2155       // Automatic Reference Counting:
2156       //   If the pseudo-expression names a retainable object with weak or
2157       //   strong lifetime, the object shall be released.
2158       Expr *BaseExpr = PseudoDtor->getBase();
2159       llvm::Value *BaseValue = NULL;
2160       Qualifiers BaseQuals;
2161 
2162       // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
2163       if (PseudoDtor->isArrow()) {
2164         BaseValue = EmitScalarExpr(BaseExpr);
2165         const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
2166         BaseQuals = PTy->getPointeeType().getQualifiers();
2167       } else {
2168         LValue BaseLV = EmitLValue(BaseExpr);
2169         BaseValue = BaseLV.getAddress();
2170         QualType BaseTy = BaseExpr->getType();
2171         BaseQuals = BaseTy.getQualifiers();
2172       }
2173 
2174       switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
2175       case Qualifiers::OCL_None:
2176       case Qualifiers::OCL_ExplicitNone:
2177       case Qualifiers::OCL_Autoreleasing:
2178         break;
2179 
2180       case Qualifiers::OCL_Strong:
2181         EmitARCRelease(Builder.CreateLoad(BaseValue,
2182                           PseudoDtor->getDestroyedType().isVolatileQualified()),
2183                        /*precise*/ true);
2184         break;
2185 
2186       case Qualifiers::OCL_Weak:
2187         EmitARCDestroyWeak(BaseValue);
2188         break;
2189       }
2190     } else {
2191       // C++ [expr.pseudo]p1:
2192       //   The result shall only be used as the operand for the function call
2193       //   operator (), and the result of such a call has type void. The only
2194       //   effect is the evaluation of the postfix-expression before the dot or
2195       //   arrow.
2196       EmitScalarExpr(E->getCallee());
2197     }
2198 
2199     return RValue::get(0);
2200   }
2201 
2202   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
2203   return EmitCall(E->getCallee()->getType(), Callee, ReturnValue,
2204                   E->arg_begin(), E->arg_end(), TargetDecl);
2205 }
2206 
2207 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
2208   // Comma expressions just emit their LHS then their RHS as an l-value.
2209   if (E->getOpcode() == BO_Comma) {
2210     EmitIgnoredExpr(E->getLHS());
2211     EnsureInsertPoint();
2212     return EmitLValue(E->getRHS());
2213   }
2214 
2215   if (E->getOpcode() == BO_PtrMemD ||
2216       E->getOpcode() == BO_PtrMemI)
2217     return EmitPointerToDataMemberBinaryExpr(E);
2218 
2219   assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
2220 
2221   // Note that in all of these cases, __block variables need the RHS
2222   // evaluated first just in case the variable gets moved by the RHS.
2223 
2224   if (!hasAggregateLLVMType(E->getType())) {
2225     switch (E->getLHS()->getType().getObjCLifetime()) {
2226     case Qualifiers::OCL_Strong:
2227       return EmitARCStoreStrong(E, /*ignored*/ false).first;
2228 
2229     case Qualifiers::OCL_Autoreleasing:
2230       return EmitARCStoreAutoreleasing(E).first;
2231 
2232     // No reason to do any of these differently.
2233     case Qualifiers::OCL_None:
2234     case Qualifiers::OCL_ExplicitNone:
2235     case Qualifiers::OCL_Weak:
2236       break;
2237     }
2238 
2239     RValue RV = EmitAnyExpr(E->getRHS());
2240     LValue LV = EmitLValue(E->getLHS());
2241     EmitStoreThroughLValue(RV, LV);
2242     return LV;
2243   }
2244 
2245   if (E->getType()->isAnyComplexType())
2246     return EmitComplexAssignmentLValue(E);
2247 
2248   return EmitAggExprToLValue(E);
2249 }
2250 
2251 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
2252   RValue RV = EmitCallExpr(E);
2253 
2254   if (!RV.isScalar())
2255     return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2256 
2257   assert(E->getCallReturnType()->isReferenceType() &&
2258          "Can't have a scalar return unless the return type is a "
2259          "reference type!");
2260 
2261   return MakeAddrLValue(RV.getScalarVal(), E->getType());
2262 }
2263 
2264 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
2265   // FIXME: This shouldn't require another copy.
2266   return EmitAggExprToLValue(E);
2267 }
2268 
2269 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
2270   assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
2271          && "binding l-value to type which needs a temporary");
2272   AggValueSlot Slot = CreateAggTemp(E->getType(), "tmp");
2273   EmitCXXConstructExpr(E, Slot);
2274   return MakeAddrLValue(Slot.getAddr(), E->getType());
2275 }
2276 
2277 LValue
2278 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
2279   return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
2280 }
2281 
2282 LValue
2283 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
2284   AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
2285   Slot.setLifetimeExternallyManaged();
2286   EmitAggExpr(E->getSubExpr(), Slot);
2287   EmitCXXTemporary(E->getTemporary(), Slot.getAddr());
2288   return MakeAddrLValue(Slot.getAddr(), E->getType());
2289 }
2290 
2291 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
2292   RValue RV = EmitObjCMessageExpr(E);
2293 
2294   if (!RV.isScalar())
2295     return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2296 
2297   assert(E->getMethodDecl()->getResultType()->isReferenceType() &&
2298          "Can't have a scalar return unless the return type is a "
2299          "reference type!");
2300 
2301   return MakeAddrLValue(RV.getScalarVal(), E->getType());
2302 }
2303 
2304 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
2305   llvm::Value *V =
2306     CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true);
2307   return MakeAddrLValue(V, E->getType());
2308 }
2309 
2310 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
2311                                              const ObjCIvarDecl *Ivar) {
2312   return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
2313 }
2314 
2315 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
2316                                           llvm::Value *BaseValue,
2317                                           const ObjCIvarDecl *Ivar,
2318                                           unsigned CVRQualifiers) {
2319   return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
2320                                                    Ivar, CVRQualifiers);
2321 }
2322 
2323 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
2324   // FIXME: A lot of the code below could be shared with EmitMemberExpr.
2325   llvm::Value *BaseValue = 0;
2326   const Expr *BaseExpr = E->getBase();
2327   Qualifiers BaseQuals;
2328   QualType ObjectTy;
2329   if (E->isArrow()) {
2330     BaseValue = EmitScalarExpr(BaseExpr);
2331     ObjectTy = BaseExpr->getType()->getPointeeType();
2332     BaseQuals = ObjectTy.getQualifiers();
2333   } else {
2334     LValue BaseLV = EmitLValue(BaseExpr);
2335     // FIXME: this isn't right for bitfields.
2336     BaseValue = BaseLV.getAddress();
2337     ObjectTy = BaseExpr->getType();
2338     BaseQuals = ObjectTy.getQualifiers();
2339   }
2340 
2341   LValue LV =
2342     EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
2343                       BaseQuals.getCVRQualifiers());
2344   setObjCGCLValueClass(getContext(), E, LV);
2345   return LV;
2346 }
2347 
2348 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
2349   // Can only get l-value for message expression returning aggregate type
2350   RValue RV = EmitAnyExprToTemp(E);
2351   return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2352 }
2353 
2354 RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
2355                                  ReturnValueSlot ReturnValue,
2356                                  CallExpr::const_arg_iterator ArgBeg,
2357                                  CallExpr::const_arg_iterator ArgEnd,
2358                                  const Decl *TargetDecl) {
2359   // Get the actual function type. The callee type will always be a pointer to
2360   // function type or a block pointer type.
2361   assert(CalleeType->isFunctionPointerType() &&
2362          "Call must have function pointer type!");
2363 
2364   CalleeType = getContext().getCanonicalType(CalleeType);
2365 
2366   const FunctionType *FnType
2367     = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
2368 
2369   CallArgList Args;
2370   EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd);
2371 
2372   return EmitCall(CGM.getTypes().getFunctionInfo(Args, FnType),
2373                   Callee, ReturnValue, Args, TargetDecl);
2374 }
2375 
2376 LValue CodeGenFunction::
2377 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
2378   llvm::Value *BaseV;
2379   if (E->getOpcode() == BO_PtrMemI)
2380     BaseV = EmitScalarExpr(E->getLHS());
2381   else
2382     BaseV = EmitLValue(E->getLHS()).getAddress();
2383 
2384   llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
2385 
2386   const MemberPointerType *MPT
2387     = E->getRHS()->getType()->getAs<MemberPointerType>();
2388 
2389   llvm::Value *AddV =
2390     CGM.getCXXABI().EmitMemberDataPointerAddress(*this, BaseV, OffsetV, MPT);
2391 
2392   return MakeAddrLValue(AddV, MPT->getPointeeType());
2393 }
2394