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 "CGDebugInfo.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/AST/APValue.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "llvm/Target/TargetData.h"
24 using namespace clang;
25 using namespace CodeGen;
26 
27 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
28   : BlockFunction(cgm, *this, Builder), CGM(cgm),
29     Target(CGM.getContext().Target),
30     Builder(cgm.getModule().getContext()),
31     DebugInfo(0), IndirectBranch(0),
32     SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
33     CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
34     ConditionalBranchLevel(0), TerminateHandler(0), TrapBB(0),
35     UniqueAggrDestructorCount(0) {
36   LLVMIntTy = ConvertType(getContext().IntTy);
37   LLVMPointerWidth = Target.getPointerWidth(0);
38   Exceptions = getContext().getLangOptions().Exceptions;
39   CatchUndefined = getContext().getLangOptions().CatchUndefined;
40 }
41 
42 ASTContext &CodeGenFunction::getContext() const {
43   return CGM.getContext();
44 }
45 
46 
47 llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
48   llvm::BasicBlock *&BB = LabelMap[S];
49   if (BB) return BB;
50 
51   // Create, but don't insert, the new block.
52   return BB = createBasicBlock(S->getName());
53 }
54 
55 llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
56   llvm::Value *Res = LocalDeclMap[VD];
57   assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
58   return Res;
59 }
60 
61 llvm::Constant *
62 CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
63   return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
64 }
65 
66 const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
67   return CGM.getTypes().ConvertTypeForMem(T);
68 }
69 
70 const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
71   return CGM.getTypes().ConvertType(T);
72 }
73 
74 bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
75   return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
76     T->isMemberFunctionPointerType();
77 }
78 
79 void CodeGenFunction::EmitReturnBlock() {
80   // For cleanliness, we try to avoid emitting the return block for
81   // simple cases.
82   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
83 
84   if (CurBB) {
85     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
86 
87     // We have a valid insert point, reuse it if it is empty or there are no
88     // explicit jumps to the return block.
89     if (CurBB->empty() || ReturnBlock->use_empty()) {
90       ReturnBlock->replaceAllUsesWith(CurBB);
91       delete ReturnBlock;
92     } else
93       EmitBlock(ReturnBlock);
94     return;
95   }
96 
97   // Otherwise, if the return block is the target of a single direct
98   // branch then we can just put the code in that block instead. This
99   // cleans up functions which started with a unified return block.
100   if (ReturnBlock->hasOneUse()) {
101     llvm::BranchInst *BI =
102       dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
103     if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
104       // Reset insertion point and delete the branch.
105       Builder.SetInsertPoint(BI->getParent());
106       BI->eraseFromParent();
107       delete ReturnBlock;
108       return;
109     }
110   }
111 
112   // FIXME: We are at an unreachable point, there is no reason to emit the block
113   // unless it has uses. However, we still need a place to put the debug
114   // region.end for now.
115 
116   EmitBlock(ReturnBlock);
117 }
118 
119 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
120   assert(BreakContinueStack.empty() &&
121          "mismatched push/pop in break/continue stack!");
122   assert(BlockScopes.empty() &&
123          "did not remove all blocks from block scope map!");
124   assert(CleanupEntries.empty() &&
125          "mismatched push/pop in cleanup stack!");
126 
127   // Emit function epilog (to return).
128   EmitReturnBlock();
129 
130   // Emit debug descriptor for function end.
131   if (CGDebugInfo *DI = getDebugInfo()) {
132     DI->setLocation(EndLoc);
133     DI->EmitRegionEnd(CurFn, Builder);
134   }
135 
136   EmitFunctionEpilog(*CurFnInfo, ReturnValue);
137   EmitEndEHSpec(CurCodeDecl);
138 
139   // If someone did an indirect goto, emit the indirect goto block at the end of
140   // the function.
141   if (IndirectBranch) {
142     EmitBlock(IndirectBranch->getParent());
143     Builder.ClearInsertionPoint();
144   }
145 
146   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
147   llvm::Instruction *Ptr = AllocaInsertPt;
148   AllocaInsertPt = 0;
149   Ptr->eraseFromParent();
150 
151   // If someone took the address of a label but never did an indirect goto, we
152   // made a zero entry PHI node, which is illegal, zap it now.
153   if (IndirectBranch) {
154     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
155     if (PN->getNumIncomingValues() == 0) {
156       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
157       PN->eraseFromParent();
158     }
159   }
160 }
161 
162 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
163                                     llvm::Function *Fn,
164                                     const FunctionArgList &Args,
165                                     SourceLocation StartLoc) {
166   const Decl *D = GD.getDecl();
167 
168   DidCallStackSave = false;
169   CurCodeDecl = CurFuncDecl = D;
170   FnRetTy = RetTy;
171   CurFn = Fn;
172   assert(CurFn->isDeclaration() && "Function already has body?");
173 
174   // Pass inline keyword to optimizer if it appears explicitly on any
175   // declaration.
176   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
177     for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
178            RE = FD->redecls_end(); RI != RE; ++RI)
179       if (RI->isInlineSpecified()) {
180         Fn->addFnAttr(llvm::Attribute::InlineHint);
181         break;
182       }
183 
184   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
185 
186   // Create a marker to make it easy to insert allocas into the entryblock
187   // later.  Don't create this with the builder, because we don't want it
188   // folded.
189   llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
190   AllocaInsertPt = new llvm::BitCastInst(Undef,
191                                          llvm::Type::getInt32Ty(VMContext), "",
192                                          EntryBB);
193   if (Builder.isNamePreserving())
194     AllocaInsertPt->setName("allocapt");
195 
196   ReturnBlock = createBasicBlock("return");
197 
198   Builder.SetInsertPoint(EntryBB);
199 
200   QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0,
201                                                  false, false, 0, 0,
202                                                  /*FIXME?*/
203                                                  FunctionType::ExtInfo());
204 
205   // Emit subprogram debug descriptor.
206   if (CGDebugInfo *DI = getDebugInfo()) {
207     DI->setLocation(StartLoc);
208     DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
209   }
210 
211   // FIXME: Leaked.
212   // CC info is ignored, hopefully?
213   CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
214                                               FunctionType::ExtInfo());
215 
216   if (RetTy->isVoidType()) {
217     // Void type; nothing to return.
218     ReturnValue = 0;
219   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
220              hasAggregateLLVMType(CurFnInfo->getReturnType())) {
221     // Indirect aggregate return; emit returned value directly into sret slot.
222     // This reduces code size, and affects correctness in C++.
223     ReturnValue = CurFn->arg_begin();
224   } else {
225     ReturnValue = CreateIRTemp(RetTy, "retval");
226   }
227 
228   EmitStartEHSpec(CurCodeDecl);
229   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
230 
231   if (CXXThisDecl)
232     CXXThisValue = Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
233   if (CXXVTTDecl)
234     CXXVTTValue = Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt");
235 
236   // If any of the arguments have a variably modified type, make sure to
237   // emit the type size.
238   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
239        i != e; ++i) {
240     QualType Ty = i->second;
241 
242     if (Ty->isVariablyModifiedType())
243       EmitVLASize(Ty);
244   }
245 }
246 
247 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
248   const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
249   assert(FD->getBody());
250   EmitStmt(FD->getBody());
251 }
252 
253 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
254   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
255 
256   // Check if we should generate debug info for this function.
257   if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
258     DebugInfo = CGM.getDebugInfo();
259 
260   FunctionArgList Args;
261 
262   CurGD = GD;
263   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
264     if (MD->isInstance()) {
265       // Create the implicit 'this' decl.
266       // FIXME: I'm not entirely sure I like using a fake decl just for code
267       // generation. Maybe we can come up with a better way?
268       CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0,
269                                               FD->getLocation(),
270                                               &getContext().Idents.get("this"),
271                                               MD->getThisType(getContext()));
272       Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
273 
274       // Check if we need a VTT parameter as well.
275       if (CodeGenVTables::needsVTTParameter(GD)) {
276         // FIXME: The comment about using a fake decl above applies here too.
277         QualType T = getContext().getPointerType(getContext().VoidPtrTy);
278         CXXVTTDecl =
279           ImplicitParamDecl::Create(getContext(), 0, FD->getLocation(),
280                                     &getContext().Idents.get("vtt"), T);
281         Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
282       }
283     }
284   }
285 
286   if (FD->getNumParams()) {
287     const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
288     assert(FProto && "Function def must have prototype!");
289 
290     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
291       Args.push_back(std::make_pair(FD->getParamDecl(i),
292                                     FProto->getArgType(i)));
293   }
294 
295   SourceRange BodyRange;
296   if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
297 
298   // Emit the standard function prologue.
299   StartFunction(GD, FD->getResultType(), Fn, Args, BodyRange.getBegin());
300 
301   // Generate the body of the function.
302   if (isa<CXXDestructorDecl>(FD))
303     EmitDestructorBody(Args);
304   else if (isa<CXXConstructorDecl>(FD))
305     EmitConstructorBody(Args);
306   else
307     EmitFunctionBody(Args);
308 
309   // Emit the standard function epilogue.
310   FinishFunction(BodyRange.getEnd());
311 
312   // Destroy the 'this' declaration.
313   if (CXXThisDecl)
314     CXXThisDecl->Destroy(getContext());
315 
316   // Destroy the VTT declaration.
317   if (CXXVTTDecl)
318     CXXVTTDecl->Destroy(getContext());
319 }
320 
321 /// ContainsLabel - Return true if the statement contains a label in it.  If
322 /// this statement is not executed normally, it not containing a label means
323 /// that we can just remove the code.
324 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
325   // Null statement, not a label!
326   if (S == 0) return false;
327 
328   // If this is a label, we have to emit the code, consider something like:
329   // if (0) {  ...  foo:  bar(); }  goto foo;
330   if (isa<LabelStmt>(S))
331     return true;
332 
333   // If this is a case/default statement, and we haven't seen a switch, we have
334   // to emit the code.
335   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
336     return true;
337 
338   // If this is a switch statement, we want to ignore cases below it.
339   if (isa<SwitchStmt>(S))
340     IgnoreCaseStmts = true;
341 
342   // Scan subexpressions for verboten labels.
343   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
344        I != E; ++I)
345     if (ContainsLabel(*I, IgnoreCaseStmts))
346       return true;
347 
348   return false;
349 }
350 
351 
352 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
353 /// a constant, or if it does but contains a label, return 0.  If it constant
354 /// folds to 'true' and does not contain a label, return 1, if it constant folds
355 /// to 'false' and does not contain a label, return -1.
356 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
357   // FIXME: Rename and handle conversion of other evaluatable things
358   // to bool.
359   Expr::EvalResult Result;
360   if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
361       Result.HasSideEffects)
362     return 0;  // Not foldable, not integer or not fully evaluatable.
363 
364   if (CodeGenFunction::ContainsLabel(Cond))
365     return 0;  // Contains a label.
366 
367   return Result.Val.getInt().getBoolValue() ? 1 : -1;
368 }
369 
370 
371 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
372 /// statement) to the specified blocks.  Based on the condition, this might try
373 /// to simplify the codegen of the conditional based on the branch.
374 ///
375 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
376                                            llvm::BasicBlock *TrueBlock,
377                                            llvm::BasicBlock *FalseBlock) {
378   if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
379     return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
380 
381   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
382     // Handle X && Y in a condition.
383     if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
384       // If we have "1 && X", simplify the code.  "0 && X" would have constant
385       // folded if the case was simple enough.
386       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
387         // br(1 && X) -> br(X).
388         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
389       }
390 
391       // If we have "X && 1", simplify the code to use an uncond branch.
392       // "X && 0" would have been constant folded to 0.
393       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
394         // br(X && 1) -> br(X).
395         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
396       }
397 
398       // Emit the LHS as a conditional.  If the LHS conditional is false, we
399       // want to jump to the FalseBlock.
400       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
401       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
402       EmitBlock(LHSTrue);
403 
404       // Any temporaries created here are conditional.
405       BeginConditionalBranch();
406       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
407       EndConditionalBranch();
408 
409       return;
410     } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
411       // If we have "0 || X", simplify the code.  "1 || X" would have constant
412       // folded if the case was simple enough.
413       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
414         // br(0 || X) -> br(X).
415         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
416       }
417 
418       // If we have "X || 0", simplify the code to use an uncond branch.
419       // "X || 1" would have been constant folded to 1.
420       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
421         // br(X || 0) -> br(X).
422         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
423       }
424 
425       // Emit the LHS as a conditional.  If the LHS conditional is true, we
426       // want to jump to the TrueBlock.
427       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
428       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
429       EmitBlock(LHSFalse);
430 
431       // Any temporaries created here are conditional.
432       BeginConditionalBranch();
433       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
434       EndConditionalBranch();
435 
436       return;
437     }
438   }
439 
440   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
441     // br(!x, t, f) -> br(x, f, t)
442     if (CondUOp->getOpcode() == UnaryOperator::LNot)
443       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
444   }
445 
446   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
447     // Handle ?: operator.
448 
449     // Just ignore GNU ?: extension.
450     if (CondOp->getLHS()) {
451       // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
452       llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
453       llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
454       EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
455       EmitBlock(LHSBlock);
456       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
457       EmitBlock(RHSBlock);
458       EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
459       return;
460     }
461   }
462 
463   // Emit the code with the fully general case.
464   llvm::Value *CondV = EvaluateExprAsBool(Cond);
465   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
466 }
467 
468 /// ErrorUnsupported - Print out an error that codegen doesn't support the
469 /// specified stmt yet.
470 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
471                                        bool OmitOnError) {
472   CGM.ErrorUnsupported(S, Type, OmitOnError);
473 }
474 
475 void
476 CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
477   // If the type contains a pointer to data member we can't memset it to zero.
478   // Instead, create a null constant and copy it to the destination.
479   if (CGM.getTypes().ContainsPointerToDataMember(Ty)) {
480     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
481 
482     llvm::GlobalVariable *NullVariable =
483       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
484                                /*isConstant=*/true,
485                                llvm::GlobalVariable::PrivateLinkage,
486                                NullConstant, llvm::Twine());
487     EmitAggregateCopy(DestPtr, NullVariable, Ty, /*isVolatile=*/false);
488     return;
489   }
490 
491 
492   // Ignore empty classes in C++.
493   if (getContext().getLangOptions().CPlusPlus) {
494     if (const RecordType *RT = Ty->getAs<RecordType>()) {
495       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
496         return;
497     }
498   }
499 
500   // Otherwise, just memset the whole thing to zero.  This is legal
501   // because in LLVM, all default initializers (other than the ones we just
502   // handled above) are guaranteed to have a bit pattern of all zeros.
503   const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
504   if (DestPtr->getType() != BP)
505     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
506 
507   // Get size and alignment info for this aggregate.
508   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
509 
510   // Don't bother emitting a zero-byte memset.
511   if (TypeInfo.first == 0)
512     return;
513 
514   // FIXME: Handle variable sized types.
515   const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
516                                                     LLVMPointerWidth);
517 
518   Builder.CreateCall5(CGM.getMemSetFn(BP, IntPtr), DestPtr,
519                  llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
520                       // TypeInfo.first describes size in bits.
521                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
522                       llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
523                                              TypeInfo.second/8),
524                       llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext),
525                                              0));
526 }
527 
528 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
529   // Make sure that there is a block for the indirect goto.
530   if (IndirectBranch == 0)
531     GetIndirectGotoBlock();
532 
533   llvm::BasicBlock *BB = getBasicBlockForLabel(L);
534 
535   // Make sure the indirect branch includes all of the address-taken blocks.
536   IndirectBranch->addDestination(BB);
537   return llvm::BlockAddress::get(CurFn, BB);
538 }
539 
540 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
541   // If we already made the indirect branch for indirect goto, return its block.
542   if (IndirectBranch) return IndirectBranch->getParent();
543 
544   CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
545 
546   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
547 
548   // Create the PHI node that indirect gotos will add entries to.
549   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
550 
551   // Create the indirect branch instruction.
552   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
553   return IndirectBranch->getParent();
554 }
555 
556 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
557   llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
558 
559   assert(SizeEntry && "Did not emit size for type");
560   return SizeEntry;
561 }
562 
563 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
564   assert(Ty->isVariablyModifiedType() &&
565          "Must pass variably modified type to EmitVLASizes!");
566 
567   EnsureInsertPoint();
568 
569   if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
570     llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
571 
572     if (!SizeEntry) {
573       const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
574 
575       // Get the element size;
576       QualType ElemTy = VAT->getElementType();
577       llvm::Value *ElemSize;
578       if (ElemTy->isVariableArrayType())
579         ElemSize = EmitVLASize(ElemTy);
580       else
581         ElemSize = llvm::ConstantInt::get(SizeTy,
582             getContext().getTypeSizeInChars(ElemTy).getQuantity());
583 
584       llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
585       NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
586 
587       SizeEntry = Builder.CreateMul(ElemSize, NumElements);
588     }
589 
590     return SizeEntry;
591   }
592 
593   if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
594     EmitVLASize(AT->getElementType());
595     return 0;
596   }
597 
598   const PointerType *PT = Ty->getAs<PointerType>();
599   assert(PT && "unknown VM type!");
600   EmitVLASize(PT->getPointeeType());
601   return 0;
602 }
603 
604 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
605   if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
606     return EmitScalarExpr(E);
607   }
608   return EmitLValue(E).getAddress();
609 }
610 
611 void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
612                                        llvm::BasicBlock *CleanupExitBlock,
613                                        llvm::BasicBlock *PreviousInvokeDest,
614                                        bool EHOnly) {
615   CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock,
616                                         PreviousInvokeDest, EHOnly));
617 }
618 
619 void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
620   assert(CleanupEntries.size() >= OldCleanupStackSize &&
621          "Cleanup stack mismatch!");
622 
623   while (CleanupEntries.size() > OldCleanupStackSize)
624     EmitCleanupBlock();
625 }
626 
627 CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
628   CleanupEntry &CE = CleanupEntries.back();
629 
630   llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
631 
632   std::vector<llvm::BasicBlock *> Blocks;
633   std::swap(Blocks, CE.Blocks);
634 
635   std::vector<llvm::BranchInst *> BranchFixups;
636   std::swap(BranchFixups, CE.BranchFixups);
637 
638   bool EHOnly = CE.EHOnly;
639 
640   setInvokeDest(CE.PreviousInvokeDest);
641 
642   CleanupEntries.pop_back();
643 
644   // Check if any branch fixups pointed to the scope we just popped. If so,
645   // we can remove them.
646   for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
647     llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
648     BlockScopeMap::iterator I = BlockScopes.find(Dest);
649 
650     if (I == BlockScopes.end())
651       continue;
652 
653     assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
654 
655     if (I->second == CleanupEntries.size()) {
656       // We don't need to do this branch fixup.
657       BranchFixups[i] = BranchFixups.back();
658       BranchFixups.pop_back();
659       i--;
660       e--;
661       continue;
662     }
663   }
664 
665   llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
666   llvm::BasicBlock *EndBlock = 0;
667   if (!BranchFixups.empty()) {
668     if (!SwitchBlock)
669       SwitchBlock = createBasicBlock("cleanup.switch");
670     EndBlock = createBasicBlock("cleanup.end");
671 
672     llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
673 
674     Builder.SetInsertPoint(SwitchBlock);
675 
676     llvm::Value *DestCodePtr
677       = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
678                          "cleanup.dst");
679     llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
680 
681     // Create a switch instruction to determine where to jump next.
682     llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
683                                                 BranchFixups.size());
684 
685     // Restore the current basic block (if any)
686     if (CurBB) {
687       Builder.SetInsertPoint(CurBB);
688 
689       // If we had a current basic block, we also need to emit an instruction
690       // to initialize the cleanup destination.
691       Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
692                           DestCodePtr);
693     } else
694       Builder.ClearInsertionPoint();
695 
696     for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
697       llvm::BranchInst *BI = BranchFixups[i];
698       llvm::BasicBlock *Dest = BI->getSuccessor(0);
699 
700       // Fixup the branch instruction to point to the cleanup block.
701       BI->setSuccessor(0, CleanupEntryBlock);
702 
703       if (CleanupEntries.empty()) {
704         llvm::ConstantInt *ID;
705 
706         // Check if we already have a destination for this block.
707         if (Dest == SI->getDefaultDest())
708           ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
709         else {
710           ID = SI->findCaseDest(Dest);
711           if (!ID) {
712             // No code found, get a new unique one by using the number of
713             // switch successors.
714             ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
715                                         SI->getNumSuccessors());
716             SI->addCase(ID, Dest);
717           }
718         }
719 
720         // Store the jump destination before the branch instruction.
721         new llvm::StoreInst(ID, DestCodePtr, BI);
722       } else {
723         // We need to jump through another cleanup block. Create a pad block
724         // with a branch instruction that jumps to the final destination and add
725         // it as a branch fixup to the current cleanup scope.
726 
727         // Create the pad block.
728         llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
729 
730         // Create a unique case ID.
731         llvm::ConstantInt *ID
732           = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
733                                    SI->getNumSuccessors());
734 
735         // Store the jump destination before the branch instruction.
736         new llvm::StoreInst(ID, DestCodePtr, BI);
737 
738         // Add it as the destination.
739         SI->addCase(ID, CleanupPad);
740 
741         // Create the branch to the final destination.
742         llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
743         CleanupPad->getInstList().push_back(BI);
744 
745         // And add it as a branch fixup.
746         CleanupEntries.back().BranchFixups.push_back(BI);
747       }
748     }
749   }
750 
751   // Remove all blocks from the block scope map.
752   for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
753     assert(BlockScopes.count(Blocks[i]) &&
754            "Did not find block in scope map!");
755 
756     BlockScopes.erase(Blocks[i]);
757   }
758 
759   return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly);
760 }
761 
762 void CodeGenFunction::EmitCleanupBlock() {
763   CleanupBlockInfo Info = PopCleanupBlock();
764 
765   if (Info.EHOnly) {
766     // FIXME: Add this to the exceptional edge
767     if (Info.CleanupBlock->getNumUses() == 0)
768       delete Info.CleanupBlock;
769     return;
770   }
771 
772   //  Scrub debug location info.
773   for (llvm::BasicBlock::iterator LBI = Info.CleanupBlock->begin(),
774          LBE = Info.CleanupBlock->end(); LBI != LBE; ++LBI)
775     Builder.SetInstDebugLocation(LBI);
776 
777   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
778   if (CurBB && !CurBB->getTerminator() &&
779       Info.CleanupBlock->getNumUses() == 0) {
780     CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
781     delete Info.CleanupBlock;
782   } else
783     EmitBlock(Info.CleanupBlock);
784 
785   if (Info.SwitchBlock)
786     EmitBlock(Info.SwitchBlock);
787   if (Info.EndBlock)
788     EmitBlock(Info.EndBlock);
789 }
790 
791 void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
792   assert(!CleanupEntries.empty() &&
793          "Trying to add branch fixup without cleanup block!");
794 
795   // FIXME: We could be more clever here and check if there's already a branch
796   // fixup for this destination and recycle it.
797   CleanupEntries.back().BranchFixups.push_back(BI);
798 }
799 
800 void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
801   if (!HaveInsertPoint())
802     return;
803 
804   llvm::BranchInst* BI = Builder.CreateBr(Dest);
805 
806   Builder.ClearInsertionPoint();
807 
808   // The stack is empty, no need to do any cleanup.
809   if (CleanupEntries.empty())
810     return;
811 
812   if (!Dest->getParent()) {
813     // We are trying to branch to a block that hasn't been inserted yet.
814     AddBranchFixup(BI);
815     return;
816   }
817 
818   BlockScopeMap::iterator I = BlockScopes.find(Dest);
819   if (I == BlockScopes.end()) {
820     // We are trying to jump to a block that is outside of any cleanup scope.
821     AddBranchFixup(BI);
822     return;
823   }
824 
825   assert(I->second < CleanupEntries.size() &&
826          "Trying to branch into cleanup region");
827 
828   if (I->second == CleanupEntries.size() - 1) {
829     // We have a branch to a block in the same scope.
830     return;
831   }
832 
833   AddBranchFixup(BI);
834 }
835