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