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