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