1 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
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 coordinates the per-function state used while generating code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CodeGenModule.h"
16 #include "CGCXXABI.h"
17 #include "CGDebugInfo.h"
18 #include "CGException.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "clang/AST/APValue.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/Frontend/CodeGenOptions.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Intrinsics.h"
28 using namespace clang;
29 using namespace CodeGen;
30 
31 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
32   : CodeGenTypeCache(cgm), CGM(cgm),
33     Target(CGM.getContext().getTargetInfo()), Builder(cgm.getModule().getContext()),
34     AutoreleaseResult(false), BlockInfo(0), BlockPointer(0),
35     NormalCleanupDest(0), NextCleanupDestIndex(1),
36     EHResumeBlock(0), ExceptionSlot(0), EHSelectorSlot(0),
37     DebugInfo(0), DisableDebugInfo(false), DidCallStackSave(false),
38     IndirectBranch(0), SwitchInsn(0), CaseRangeBlock(0), UnreachableBlock(0),
39     CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
40     OutermostConditional(0), TerminateLandingPad(0), TerminateHandler(0),
41     TrapBB(0) {
42 
43   CatchUndefined = getContext().getLangOptions().CatchUndefined;
44   CGM.getCXXABI().getMangleContext().startNewFunction();
45 }
46 
47 
48 llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
49   return CGM.getTypes().ConvertTypeForMem(T);
50 }
51 
52 llvm::Type *CodeGenFunction::ConvertType(QualType T) {
53   return CGM.getTypes().ConvertType(T);
54 }
55 
56 bool CodeGenFunction::hasAggregateLLVMType(QualType type) {
57   switch (type.getCanonicalType()->getTypeClass()) {
58 #define TYPE(name, parent)
59 #define ABSTRACT_TYPE(name, parent)
60 #define NON_CANONICAL_TYPE(name, parent) case Type::name:
61 #define DEPENDENT_TYPE(name, parent) case Type::name:
62 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
63 #include "clang/AST/TypeNodes.def"
64     llvm_unreachable("non-canonical or dependent type in IR-generation");
65 
66   case Type::Builtin:
67   case Type::Pointer:
68   case Type::BlockPointer:
69   case Type::LValueReference:
70   case Type::RValueReference:
71   case Type::MemberPointer:
72   case Type::Vector:
73   case Type::ExtVector:
74   case Type::FunctionProto:
75   case Type::FunctionNoProto:
76   case Type::Enum:
77   case Type::ObjCObjectPointer:
78     return false;
79 
80   // Complexes, arrays, records, and Objective-C objects.
81   case Type::Complex:
82   case Type::ConstantArray:
83   case Type::IncompleteArray:
84   case Type::VariableArray:
85   case Type::Record:
86   case Type::ObjCObject:
87   case Type::ObjCInterface:
88     return true;
89   }
90   llvm_unreachable("unknown type kind!");
91 }
92 
93 void CodeGenFunction::EmitReturnBlock() {
94   // For cleanliness, we try to avoid emitting the return block for
95   // simple cases.
96   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
97 
98   if (CurBB) {
99     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
100 
101     // We have a valid insert point, reuse it if it is empty or there are no
102     // explicit jumps to the return block.
103     if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
104       ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
105       delete ReturnBlock.getBlock();
106     } else
107       EmitBlock(ReturnBlock.getBlock());
108     return;
109   }
110 
111   // Otherwise, if the return block is the target of a single direct
112   // branch then we can just put the code in that block instead. This
113   // cleans up functions which started with a unified return block.
114   if (ReturnBlock.getBlock()->hasOneUse()) {
115     llvm::BranchInst *BI =
116       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin());
117     if (BI && BI->isUnconditional() &&
118         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
119       // Reset insertion point, including debug location, and delete the branch.
120       Builder.SetCurrentDebugLocation(BI->getDebugLoc());
121       Builder.SetInsertPoint(BI->getParent());
122       BI->eraseFromParent();
123       delete ReturnBlock.getBlock();
124       return;
125     }
126   }
127 
128   // FIXME: We are at an unreachable point, there is no reason to emit the block
129   // unless it has uses. However, we still need a place to put the debug
130   // region.end for now.
131 
132   EmitBlock(ReturnBlock.getBlock());
133 }
134 
135 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
136   if (!BB) return;
137   if (!BB->use_empty())
138     return CGF.CurFn->getBasicBlockList().push_back(BB);
139   delete BB;
140 }
141 
142 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
143   assert(BreakContinueStack.empty() &&
144          "mismatched push/pop in break/continue stack!");
145 
146   // Pop any cleanups that might have been associated with the
147   // parameters.  Do this in whatever block we're currently in; it's
148   // important to do this before we enter the return block or return
149   // edges will be *really* confused.
150   if (EHStack.stable_begin() != PrologueCleanupDepth)
151     PopCleanupBlocks(PrologueCleanupDepth);
152 
153   // Emit function epilog (to return).
154   EmitReturnBlock();
155 
156   if (ShouldInstrumentFunction())
157     EmitFunctionInstrumentation("__cyg_profile_func_exit");
158 
159   // Emit debug descriptor for function end.
160   if (CGDebugInfo *DI = getDebugInfo()) {
161     DI->setLocation(EndLoc);
162     DI->EmitFunctionEnd(Builder);
163   }
164 
165   EmitFunctionEpilog(*CurFnInfo);
166   EmitEndEHSpec(CurCodeDecl);
167 
168   assert(EHStack.empty() &&
169          "did not remove all scopes from cleanup stack!");
170 
171   // If someone did an indirect goto, emit the indirect goto block at the end of
172   // the function.
173   if (IndirectBranch) {
174     EmitBlock(IndirectBranch->getParent());
175     Builder.ClearInsertionPoint();
176   }
177 
178   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
179   llvm::Instruction *Ptr = AllocaInsertPt;
180   AllocaInsertPt = 0;
181   Ptr->eraseFromParent();
182 
183   // If someone took the address of a label but never did an indirect goto, we
184   // made a zero entry PHI node, which is illegal, zap it now.
185   if (IndirectBranch) {
186     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
187     if (PN->getNumIncomingValues() == 0) {
188       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
189       PN->eraseFromParent();
190     }
191   }
192 
193   EmitIfUsed(*this, EHResumeBlock);
194   EmitIfUsed(*this, TerminateLandingPad);
195   EmitIfUsed(*this, TerminateHandler);
196   EmitIfUsed(*this, UnreachableBlock);
197 
198   if (CGM.getCodeGenOpts().EmitDeclMetadata)
199     EmitDeclMetadata();
200 }
201 
202 /// ShouldInstrumentFunction - Return true if the current function should be
203 /// instrumented with __cyg_profile_func_* calls
204 bool CodeGenFunction::ShouldInstrumentFunction() {
205   if (!CGM.getCodeGenOpts().InstrumentFunctions)
206     return false;
207   if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
208     return false;
209   return true;
210 }
211 
212 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
213 /// instrumentation function with the current function and the call site, if
214 /// function instrumentation is enabled.
215 void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
216   // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
217   llvm::PointerType *PointerTy = Int8PtrTy;
218   llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
219   llvm::FunctionType *FunctionTy =
220     llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
221                             ProfileFuncArgs, false);
222 
223   llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
224   llvm::CallInst *CallSite = Builder.CreateCall(
225     CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
226     llvm::ConstantInt::get(Int32Ty, 0),
227     "callsite");
228 
229   Builder.CreateCall2(F,
230                       llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
231                       CallSite);
232 }
233 
234 void CodeGenFunction::EmitMCountInstrumentation() {
235   llvm::FunctionType *FTy =
236     llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), false);
237 
238   llvm::Constant *MCountFn = CGM.CreateRuntimeFunction(FTy,
239                                                        Target.getMCountName());
240   Builder.CreateCall(MCountFn);
241 }
242 
243 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
244                                     llvm::Function *Fn,
245                                     const CGFunctionInfo &FnInfo,
246                                     const FunctionArgList &Args,
247                                     SourceLocation StartLoc) {
248   const Decl *D = GD.getDecl();
249 
250   DidCallStackSave = false;
251   CurCodeDecl = CurFuncDecl = D;
252   FnRetTy = RetTy;
253   CurFn = Fn;
254   CurFnInfo = &FnInfo;
255   assert(CurFn->isDeclaration() && "Function already has body?");
256 
257   // Pass inline keyword to optimizer if it appears explicitly on any
258   // declaration.
259   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
260     for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
261            RE = FD->redecls_end(); RI != RE; ++RI)
262       if (RI->isInlineSpecified()) {
263         Fn->addFnAttr(llvm::Attribute::InlineHint);
264         break;
265       }
266 
267   if (getContext().getLangOptions().OpenCL) {
268     // Add metadata for a kernel function.
269     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
270       if (FD->hasAttr<OpenCLKernelAttr>()) {
271         llvm::LLVMContext &Context = getLLVMContext();
272         llvm::NamedMDNode *OpenCLMetadata =
273           CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
274 
275         llvm::Value *Op = Fn;
276         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Op));
277       }
278   }
279 
280   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
281 
282   // Create a marker to make it easy to insert allocas into the entryblock
283   // later.  Don't create this with the builder, because we don't want it
284   // folded.
285   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
286   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
287   if (Builder.isNamePreserving())
288     AllocaInsertPt->setName("allocapt");
289 
290   ReturnBlock = getJumpDestInCurrentScope("return");
291 
292   Builder.SetInsertPoint(EntryBB);
293 
294   // Emit subprogram debug descriptor.
295   if (CGDebugInfo *DI = getDebugInfo()) {
296     // FIXME: what is going on here and why does it ignore all these
297     // interesting type properties?
298     QualType FnType =
299       getContext().getFunctionType(RetTy, 0, 0,
300                                    FunctionProtoType::ExtProtoInfo());
301 
302     DI->setLocation(StartLoc);
303     DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
304   }
305 
306   if (ShouldInstrumentFunction())
307     EmitFunctionInstrumentation("__cyg_profile_func_enter");
308 
309   if (CGM.getCodeGenOpts().InstrumentForProfiling)
310     EmitMCountInstrumentation();
311 
312   if (RetTy->isVoidType()) {
313     // Void type; nothing to return.
314     ReturnValue = 0;
315   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
316              hasAggregateLLVMType(CurFnInfo->getReturnType())) {
317     // Indirect aggregate return; emit returned value directly into sret slot.
318     // This reduces code size, and affects correctness in C++.
319     ReturnValue = CurFn->arg_begin();
320   } else {
321     ReturnValue = CreateIRTemp(RetTy, "retval");
322 
323     // Tell the epilog emitter to autorelease the result.  We do this
324     // now so that various specialized functions can suppress it
325     // during their IR-generation.
326     if (getLangOptions().ObjCAutoRefCount &&
327         !CurFnInfo->isReturnsRetained() &&
328         RetTy->isObjCRetainableType())
329       AutoreleaseResult = true;
330   }
331 
332   EmitStartEHSpec(CurCodeDecl);
333 
334   PrologueCleanupDepth = EHStack.stable_begin();
335   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
336 
337   if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
338     CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
339 
340   // If any of the arguments have a variably modified type, make sure to
341   // emit the type size.
342   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
343        i != e; ++i) {
344     QualType Ty = (*i)->getType();
345 
346     if (Ty->isVariablyModifiedType())
347       EmitVariablyModifiedType(Ty);
348   }
349 }
350 
351 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
352   const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
353   assert(FD->getBody());
354   EmitStmt(FD->getBody());
355 }
356 
357 /// Tries to mark the given function nounwind based on the
358 /// non-existence of any throwing calls within it.  We believe this is
359 /// lightweight enough to do at -O0.
360 static void TryMarkNoThrow(llvm::Function *F) {
361   // LLVM treats 'nounwind' on a function as part of the type, so we
362   // can't do this on functions that can be overwritten.
363   if (F->mayBeOverridden()) return;
364 
365   for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
366     for (llvm::BasicBlock::iterator
367            BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
368       if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI))
369         if (!Call->doesNotThrow())
370           return;
371   F->setDoesNotThrow(true);
372 }
373 
374 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
375                                    const CGFunctionInfo &FnInfo) {
376   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
377 
378   // Check if we should generate debug info for this function.
379   if (CGM.getModuleDebugInfo() && !FD->hasAttr<NoDebugAttr>())
380     DebugInfo = CGM.getModuleDebugInfo();
381 
382   FunctionArgList Args;
383   QualType ResTy = FD->getResultType();
384 
385   CurGD = GD;
386   if (isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isInstance())
387     CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args);
388 
389   if (FD->getNumParams())
390     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
391       Args.push_back(FD->getParamDecl(i));
392 
393   SourceRange BodyRange;
394   if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
395 
396   // Emit the standard function prologue.
397   StartFunction(GD, ResTy, Fn, FnInfo, Args, BodyRange.getBegin());
398 
399   // Generate the body of the function.
400   if (isa<CXXDestructorDecl>(FD))
401     EmitDestructorBody(Args);
402   else if (isa<CXXConstructorDecl>(FD))
403     EmitConstructorBody(Args);
404   else
405     EmitFunctionBody(Args);
406 
407   // Emit the standard function epilogue.
408   FinishFunction(BodyRange.getEnd());
409 
410   // If we haven't marked the function nothrow through other means, do
411   // a quick pass now to see if we can.
412   if (!CurFn->doesNotThrow())
413     TryMarkNoThrow(CurFn);
414 }
415 
416 /// ContainsLabel - Return true if the statement contains a label in it.  If
417 /// this statement is not executed normally, it not containing a label means
418 /// that we can just remove the code.
419 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
420   // Null statement, not a label!
421   if (S == 0) return false;
422 
423   // If this is a label, we have to emit the code, consider something like:
424   // if (0) {  ...  foo:  bar(); }  goto foo;
425   //
426   // TODO: If anyone cared, we could track __label__'s, since we know that you
427   // can't jump to one from outside their declared region.
428   if (isa<LabelStmt>(S))
429     return true;
430 
431   // If this is a case/default statement, and we haven't seen a switch, we have
432   // to emit the code.
433   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
434     return true;
435 
436   // If this is a switch statement, we want to ignore cases below it.
437   if (isa<SwitchStmt>(S))
438     IgnoreCaseStmts = true;
439 
440   // Scan subexpressions for verboten labels.
441   for (Stmt::const_child_range I = S->children(); I; ++I)
442     if (ContainsLabel(*I, IgnoreCaseStmts))
443       return true;
444 
445   return false;
446 }
447 
448 /// containsBreak - Return true if the statement contains a break out of it.
449 /// If the statement (recursively) contains a switch or loop with a break
450 /// inside of it, this is fine.
451 bool CodeGenFunction::containsBreak(const Stmt *S) {
452   // Null statement, not a label!
453   if (S == 0) return false;
454 
455   // If this is a switch or loop that defines its own break scope, then we can
456   // include it and anything inside of it.
457   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
458       isa<ForStmt>(S))
459     return false;
460 
461   if (isa<BreakStmt>(S))
462     return true;
463 
464   // Scan subexpressions for verboten breaks.
465   for (Stmt::const_child_range I = S->children(); I; ++I)
466     if (containsBreak(*I))
467       return true;
468 
469   return false;
470 }
471 
472 
473 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
474 /// to a constant, or if it does but contains a label, return false.  If it
475 /// constant folds return true and set the boolean result in Result.
476 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
477                                                    bool &ResultBool) {
478   llvm::APInt ResultInt;
479   if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
480     return false;
481 
482   ResultBool = ResultInt.getBoolValue();
483   return true;
484 }
485 
486 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
487 /// to a constant, or if it does but contains a label, return false.  If it
488 /// constant folds return true and set the folded value.
489 bool CodeGenFunction::
490 ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APInt &ResultInt) {
491   // FIXME: Rename and handle conversion of other evaluatable things
492   // to bool.
493   Expr::EvalResult Result;
494   if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
495       Result.HasSideEffects)
496     return false;  // Not foldable, not integer or not fully evaluatable.
497 
498   if (CodeGenFunction::ContainsLabel(Cond))
499     return false;  // Contains a label.
500 
501   ResultInt = Result.Val.getInt();
502   return true;
503 }
504 
505 
506 
507 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
508 /// statement) to the specified blocks.  Based on the condition, this might try
509 /// to simplify the codegen of the conditional based on the branch.
510 ///
511 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
512                                            llvm::BasicBlock *TrueBlock,
513                                            llvm::BasicBlock *FalseBlock) {
514   Cond = Cond->IgnoreParens();
515 
516   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
517     // Handle X && Y in a condition.
518     if (CondBOp->getOpcode() == BO_LAnd) {
519       // If we have "1 && X", simplify the code.  "0 && X" would have constant
520       // folded if the case was simple enough.
521       bool ConstantBool = false;
522       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
523           ConstantBool) {
524         // br(1 && X) -> br(X).
525         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
526       }
527 
528       // If we have "X && 1", simplify the code to use an uncond branch.
529       // "X && 0" would have been constant folded to 0.
530       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
531           ConstantBool) {
532         // br(X && 1) -> br(X).
533         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
534       }
535 
536       // Emit the LHS as a conditional.  If the LHS conditional is false, we
537       // want to jump to the FalseBlock.
538       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
539 
540       ConditionalEvaluation eval(*this);
541       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
542       EmitBlock(LHSTrue);
543 
544       // Any temporaries created here are conditional.
545       eval.begin(*this);
546       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
547       eval.end(*this);
548 
549       return;
550     }
551 
552     if (CondBOp->getOpcode() == BO_LOr) {
553       // If we have "0 || X", simplify the code.  "1 || X" would have constant
554       // folded if the case was simple enough.
555       bool ConstantBool = false;
556       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
557           !ConstantBool) {
558         // br(0 || X) -> br(X).
559         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
560       }
561 
562       // If we have "X || 0", simplify the code to use an uncond branch.
563       // "X || 1" would have been constant folded to 1.
564       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
565           !ConstantBool) {
566         // br(X || 0) -> br(X).
567         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
568       }
569 
570       // Emit the LHS as a conditional.  If the LHS conditional is true, we
571       // want to jump to the TrueBlock.
572       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
573 
574       ConditionalEvaluation eval(*this);
575       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
576       EmitBlock(LHSFalse);
577 
578       // Any temporaries created here are conditional.
579       eval.begin(*this);
580       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
581       eval.end(*this);
582 
583       return;
584     }
585   }
586 
587   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
588     // br(!x, t, f) -> br(x, f, t)
589     if (CondUOp->getOpcode() == UO_LNot)
590       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
591   }
592 
593   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
594     // Handle ?: operator.
595 
596     // Just ignore GNU ?: extension.
597     if (CondOp->getLHS()) {
598       // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
599       llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
600       llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
601 
602       ConditionalEvaluation cond(*this);
603       EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
604 
605       cond.begin(*this);
606       EmitBlock(LHSBlock);
607       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
608       cond.end(*this);
609 
610       cond.begin(*this);
611       EmitBlock(RHSBlock);
612       EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
613       cond.end(*this);
614 
615       return;
616     }
617   }
618 
619   // Emit the code with the fully general case.
620   llvm::Value *CondV = EvaluateExprAsBool(Cond);
621   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
622 }
623 
624 /// ErrorUnsupported - Print out an error that codegen doesn't support the
625 /// specified stmt yet.
626 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
627                                        bool OmitOnError) {
628   CGM.ErrorUnsupported(S, Type, OmitOnError);
629 }
630 
631 /// emitNonZeroVLAInit - Emit the "zero" initialization of a
632 /// variable-length array whose elements have a non-zero bit-pattern.
633 ///
634 /// \param src - a char* pointing to the bit-pattern for a single
635 /// base element of the array
636 /// \param sizeInChars - the total size of the VLA, in chars
637 /// \param align - the total alignment of the VLA
638 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
639                                llvm::Value *dest, llvm::Value *src,
640                                llvm::Value *sizeInChars) {
641   std::pair<CharUnits,CharUnits> baseSizeAndAlign
642     = CGF.getContext().getTypeInfoInChars(baseType);
643 
644   CGBuilderTy &Builder = CGF.Builder;
645 
646   llvm::Value *baseSizeInChars
647     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
648 
649   llvm::Type *i8p = Builder.getInt8PtrTy();
650 
651   llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
652   llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
653 
654   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
655   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
656   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
657 
658   // Make a loop over the VLA.  C99 guarantees that the VLA element
659   // count must be nonzero.
660   CGF.EmitBlock(loopBB);
661 
662   llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur");
663   cur->addIncoming(begin, originBB);
664 
665   // memcpy the individual element bit-pattern.
666   Builder.CreateMemCpy(cur, src, baseSizeInChars,
667                        baseSizeAndAlign.second.getQuantity(),
668                        /*volatile*/ false);
669 
670   // Go to the next element.
671   llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next");
672 
673   // Leave if that's the end of the VLA.
674   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
675   Builder.CreateCondBr(done, contBB, loopBB);
676   cur->addIncoming(next, loopBB);
677 
678   CGF.EmitBlock(contBB);
679 }
680 
681 void
682 CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
683   // Ignore empty classes in C++.
684   if (getContext().getLangOptions().CPlusPlus) {
685     if (const RecordType *RT = Ty->getAs<RecordType>()) {
686       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
687         return;
688     }
689   }
690 
691   // Cast the dest ptr to the appropriate i8 pointer type.
692   unsigned DestAS =
693     cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
694   llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
695   if (DestPtr->getType() != BP)
696     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
697 
698   // Get size and alignment info for this aggregate.
699   std::pair<CharUnits, CharUnits> TypeInfo =
700     getContext().getTypeInfoInChars(Ty);
701   CharUnits Size = TypeInfo.first;
702   CharUnits Align = TypeInfo.second;
703 
704   llvm::Value *SizeVal;
705   const VariableArrayType *vla;
706 
707   // Don't bother emitting a zero-byte memset.
708   if (Size.isZero()) {
709     // But note that getTypeInfo returns 0 for a VLA.
710     if (const VariableArrayType *vlaType =
711           dyn_cast_or_null<VariableArrayType>(
712                                           getContext().getAsArrayType(Ty))) {
713       QualType eltType;
714       llvm::Value *numElts;
715       llvm::tie(numElts, eltType) = getVLASize(vlaType);
716 
717       SizeVal = numElts;
718       CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
719       if (!eltSize.isOne())
720         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
721       vla = vlaType;
722     } else {
723       return;
724     }
725   } else {
726     SizeVal = CGM.getSize(Size);
727     vla = 0;
728   }
729 
730   // If the type contains a pointer to data member we can't memset it to zero.
731   // Instead, create a null constant and copy it to the destination.
732   // TODO: there are other patterns besides zero that we can usefully memset,
733   // like -1, which happens to be the pattern used by member-pointers.
734   if (!CGM.getTypes().isZeroInitializable(Ty)) {
735     // For a VLA, emit a single element, then splat that over the VLA.
736     if (vla) Ty = getContext().getBaseElementType(vla);
737 
738     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
739 
740     llvm::GlobalVariable *NullVariable =
741       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
742                                /*isConstant=*/true,
743                                llvm::GlobalVariable::PrivateLinkage,
744                                NullConstant, Twine());
745     llvm::Value *SrcPtr =
746       Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
747 
748     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
749 
750     // Get and call the appropriate llvm.memcpy overload.
751     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false);
752     return;
753   }
754 
755   // Otherwise, just memset the whole thing to zero.  This is legal
756   // because in LLVM, all default initializers (other than the ones we just
757   // handled above) are guaranteed to have a bit pattern of all zeros.
758   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal,
759                        Align.getQuantity(), false);
760 }
761 
762 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
763   // Make sure that there is a block for the indirect goto.
764   if (IndirectBranch == 0)
765     GetIndirectGotoBlock();
766 
767   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
768 
769   // Make sure the indirect branch includes all of the address-taken blocks.
770   IndirectBranch->addDestination(BB);
771   return llvm::BlockAddress::get(CurFn, BB);
772 }
773 
774 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
775   // If we already made the indirect branch for indirect goto, return its block.
776   if (IndirectBranch) return IndirectBranch->getParent();
777 
778   CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
779 
780   // Create the PHI node that indirect gotos will add entries to.
781   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
782                                               "indirect.goto.dest");
783 
784   // Create the indirect branch instruction.
785   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
786   return IndirectBranch->getParent();
787 }
788 
789 /// Computes the length of an array in elements, as well as the base
790 /// element type and a properly-typed first element pointer.
791 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
792                                               QualType &baseType,
793                                               llvm::Value *&addr) {
794   const ArrayType *arrayType = origArrayType;
795 
796   // If it's a VLA, we have to load the stored size.  Note that
797   // this is the size of the VLA in bytes, not its size in elements.
798   llvm::Value *numVLAElements = 0;
799   if (isa<VariableArrayType>(arrayType)) {
800     numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
801 
802     // Walk into all VLAs.  This doesn't require changes to addr,
803     // which has type T* where T is the first non-VLA element type.
804     do {
805       QualType elementType = arrayType->getElementType();
806       arrayType = getContext().getAsArrayType(elementType);
807 
808       // If we only have VLA components, 'addr' requires no adjustment.
809       if (!arrayType) {
810         baseType = elementType;
811         return numVLAElements;
812       }
813     } while (isa<VariableArrayType>(arrayType));
814 
815     // We get out here only if we find a constant array type
816     // inside the VLA.
817   }
818 
819   // We have some number of constant-length arrays, so addr should
820   // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
821   // down to the first element of addr.
822   SmallVector<llvm::Value*, 8> gepIndices;
823 
824   // GEP down to the array type.
825   llvm::ConstantInt *zero = Builder.getInt32(0);
826   gepIndices.push_back(zero);
827 
828   // It's more efficient to calculate the count from the LLVM
829   // constant-length arrays than to re-evaluate the array bounds.
830   uint64_t countFromCLAs = 1;
831 
832   llvm::ArrayType *llvmArrayType =
833     cast<llvm::ArrayType>(
834       cast<llvm::PointerType>(addr->getType())->getElementType());
835   while (true) {
836     assert(isa<ConstantArrayType>(arrayType));
837     assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
838              == llvmArrayType->getNumElements());
839 
840     gepIndices.push_back(zero);
841     countFromCLAs *= llvmArrayType->getNumElements();
842 
843     llvmArrayType =
844       dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
845     if (!llvmArrayType) break;
846 
847     arrayType = getContext().getAsArrayType(arrayType->getElementType());
848     assert(arrayType && "LLVM and Clang types are out-of-synch");
849   }
850 
851   baseType = arrayType->getElementType();
852 
853   // Create the actual GEP.
854   addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin");
855 
856   llvm::Value *numElements
857     = llvm::ConstantInt::get(SizeTy, countFromCLAs);
858 
859   // If we had any VLA dimensions, factor them in.
860   if (numVLAElements)
861     numElements = Builder.CreateNUWMul(numVLAElements, numElements);
862 
863   return numElements;
864 }
865 
866 std::pair<llvm::Value*, QualType>
867 CodeGenFunction::getVLASize(QualType type) {
868   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
869   assert(vla && "type was not a variable array type!");
870   return getVLASize(vla);
871 }
872 
873 std::pair<llvm::Value*, QualType>
874 CodeGenFunction::getVLASize(const VariableArrayType *type) {
875   // The number of elements so far; always size_t.
876   llvm::Value *numElements = 0;
877 
878   QualType elementType;
879   do {
880     elementType = type->getElementType();
881     llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
882     assert(vlaSize && "no size for VLA!");
883     assert(vlaSize->getType() == SizeTy);
884 
885     if (!numElements) {
886       numElements = vlaSize;
887     } else {
888       // It's undefined behavior if this wraps around, so mark it that way.
889       numElements = Builder.CreateNUWMul(numElements, vlaSize);
890     }
891   } while ((type = getContext().getAsVariableArrayType(elementType)));
892 
893   return std::pair<llvm::Value*,QualType>(numElements, elementType);
894 }
895 
896 void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
897   assert(type->isVariablyModifiedType() &&
898          "Must pass variably modified type to EmitVLASizes!");
899 
900   EnsureInsertPoint();
901 
902   // We're going to walk down into the type and look for VLA
903   // expressions.
904   type = type.getCanonicalType();
905   do {
906     assert(type->isVariablyModifiedType());
907 
908     const Type *ty = type.getTypePtr();
909     switch (ty->getTypeClass()) {
910 #define TYPE(Class, Base)
911 #define ABSTRACT_TYPE(Class, Base)
912 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
913 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
914 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
915 #include "clang/AST/TypeNodes.def"
916       llvm_unreachable("unexpected dependent or non-canonical type!");
917 
918     // These types are never variably-modified.
919     case Type::Builtin:
920     case Type::Complex:
921     case Type::Vector:
922     case Type::ExtVector:
923     case Type::Record:
924     case Type::Enum:
925     case Type::ObjCObject:
926     case Type::ObjCInterface:
927     case Type::ObjCObjectPointer:
928       llvm_unreachable("type class is never variably-modified!");
929 
930     case Type::Pointer:
931       type = cast<PointerType>(ty)->getPointeeType();
932       break;
933 
934     case Type::BlockPointer:
935       type = cast<BlockPointerType>(ty)->getPointeeType();
936       break;
937 
938     case Type::LValueReference:
939     case Type::RValueReference:
940       type = cast<ReferenceType>(ty)->getPointeeType();
941       break;
942 
943     case Type::MemberPointer:
944       type = cast<MemberPointerType>(ty)->getPointeeType();
945       break;
946 
947     case Type::ConstantArray:
948     case Type::IncompleteArray:
949       // Losing element qualification here is fine.
950       type = cast<ArrayType>(ty)->getElementType();
951       break;
952 
953     case Type::VariableArray: {
954       // Losing element qualification here is fine.
955       const VariableArrayType *vat = cast<VariableArrayType>(ty);
956 
957       // Unknown size indication requires no size computation.
958       // Otherwise, evaluate and record it.
959       if (const Expr *size = vat->getSizeExpr()) {
960         // It's possible that we might have emitted this already,
961         // e.g. with a typedef and a pointer to it.
962         llvm::Value *&entry = VLASizeMap[size];
963         if (!entry) {
964           // Always zexting here would be wrong if it weren't
965           // undefined behavior to have a negative bound.
966           entry = Builder.CreateIntCast(EmitScalarExpr(size), SizeTy,
967                                         /*signed*/ false);
968         }
969       }
970       type = vat->getElementType();
971       break;
972     }
973 
974     case Type::FunctionProto:
975     case Type::FunctionNoProto:
976       type = cast<FunctionType>(ty)->getResultType();
977       break;
978     }
979   } while (type->isVariablyModifiedType());
980 }
981 
982 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
983   if (getContext().getBuiltinVaListType()->isArrayType())
984     return EmitScalarExpr(E);
985   return EmitLValue(E).getAddress();
986 }
987 
988 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
989                                               llvm::Constant *Init) {
990   assert (Init && "Invalid DeclRefExpr initializer!");
991   if (CGDebugInfo *Dbg = getDebugInfo())
992     Dbg->EmitGlobalVariable(E->getDecl(), Init);
993 }
994 
995 CodeGenFunction::PeepholeProtection
996 CodeGenFunction::protectFromPeepholes(RValue rvalue) {
997   // At the moment, the only aggressive peephole we do in IR gen
998   // is trunc(zext) folding, but if we add more, we can easily
999   // extend this protection.
1000 
1001   if (!rvalue.isScalar()) return PeepholeProtection();
1002   llvm::Value *value = rvalue.getScalarVal();
1003   if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
1004 
1005   // Just make an extra bitcast.
1006   assert(HaveInsertPoint());
1007   llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
1008                                                   Builder.GetInsertBlock());
1009 
1010   PeepholeProtection protection;
1011   protection.Inst = inst;
1012   return protection;
1013 }
1014 
1015 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
1016   if (!protection.Inst) return;
1017 
1018   // In theory, we could try to duplicate the peepholes now, but whatever.
1019   protection.Inst->eraseFromParent();
1020 }
1021