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 "llvm/Support/CFG.h"
22 using namespace clang;
23 using namespace CodeGen;
24 
25 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
26   : CGM(cgm), Target(CGM.getContext().Target), SwitchInsn(NULL),
27     CaseRangeBlock(NULL) {
28     LLVMIntTy = ConvertType(getContext().IntTy);
29     LLVMPointerWidth = Target.getPointerWidth(0);
30 }
31 
32 ASTContext &CodeGenFunction::getContext() const {
33   return CGM.getContext();
34 }
35 
36 
37 llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
38   llvm::BasicBlock *&BB = LabelMap[S];
39   if (BB) return BB;
40 
41   // Create, but don't insert, the new block.
42   return BB = createBasicBlock(S->getName());
43 }
44 
45 llvm::Constant *
46 CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
47   return cast<llvm::Constant>(LocalDeclMap[BVD]);
48 }
49 
50 llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD)
51 {
52   return LocalDeclMap[VD];
53 }
54 
55 const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
56   return CGM.getTypes().ConvertType(T);
57 }
58 
59 bool CodeGenFunction::isObjCPointerType(QualType T) {
60   // All Objective-C types are pointers.
61   return T->isObjCInterfaceType() ||
62     T->isObjCQualifiedInterfaceType() || T->isObjCQualifiedIdType();
63 }
64 
65 bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
66   // FIXME: Use positive checks instead of negative ones to be more
67   // robust in the face of extension.
68   return !isObjCPointerType(T) &&!T->isRealType() && !T->isPointerLikeType() &&
69     !T->isVoidType() && !T->isVectorType() && !T->isFunctionType() &&
70     !T->isBlockPointerType();
71 }
72 
73 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
74   // Finish emission of indirect switches.
75   EmitIndirectSwitches();
76 
77   assert(BreakContinueStack.empty() &&
78          "mismatched push/pop in break/continue stack!");
79 
80   // Emit function epilog (to return). This has the nice side effect
81   // of also automatically handling code that falls off the end.
82   EmitBlock(ReturnBlock);
83 
84   // Emit debug descriptor for function end.
85   if (CGDebugInfo *DI = CGM.getDebugInfo()) {
86     DI->setLocation(EndLoc);
87     DI->EmitRegionEnd(CurFn, Builder);
88   }
89 
90   EmitFunctionEpilog(FnRetTy, ReturnValue);
91 
92   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
93   AllocaInsertPt->eraseFromParent();
94   AllocaInsertPt = 0;
95 }
96 
97 void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
98                                     llvm::Function *Fn,
99                                     const FunctionArgList &Args,
100                                     SourceLocation StartLoc) {
101   CurFuncDecl = D;
102   FnRetTy = RetTy;
103   CurFn = Fn;
104   assert(CurFn->isDeclaration() && "Function already has body?");
105 
106   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
107 
108   // Create a marker to make it easy to insert allocas into the entryblock
109   // later.  Don't create this with the builder, because we don't want it
110   // folded.
111   llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
112   AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
113                                          EntryBB);
114 
115   ReturnBlock = createBasicBlock("return");
116   ReturnValue = 0;
117   if (!RetTy->isVoidType())
118     ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
119 
120   Builder.SetInsertPoint(EntryBB);
121 
122   // Emit subprogram debug descriptor.
123   // FIXME: The cast here is a huge hack.
124   if (CGDebugInfo *DI = CGM.getDebugInfo()) {
125     DI->setLocation(StartLoc);
126     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
127       DI->EmitFunctionStart(FD->getIdentifier()->getName(),
128                             RetTy, CurFn, Builder);
129     } else {
130       // Just use LLVM function name.
131       DI->EmitFunctionStart(Fn->getName().c_str(),
132                             RetTy, CurFn, Builder);
133     }
134   }
135 
136   EmitFunctionProlog(CurFn, FnRetTy, Args);
137 
138   // If any of the arguments have a variably modified type, make sure to
139   // emit the type size.
140   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
141        i != e; ++i) {
142     QualType Ty = i->second;
143 
144     if (Ty->isVariablyModifiedType())
145       EmitVLASize(Ty);
146   }
147 }
148 
149 void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
150                                    llvm::Function *Fn) {
151   FunctionArgList Args;
152   if (FD->getNumParams()) {
153     const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto();
154     assert(FProto && "Function def must have prototype!");
155 
156     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
157       Args.push_back(std::make_pair(FD->getParamDecl(i),
158                                     FProto->getArgType(i)));
159   }
160 
161   StartFunction(FD, FD->getResultType(), Fn, Args,
162                 cast<CompoundStmt>(FD->getBody())->getLBracLoc());
163 
164   EmitStmt(FD->getBody());
165 
166   const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
167   if (S) {
168     FinishFunction(S->getRBracLoc());
169   } else {
170     FinishFunction();
171   }
172 }
173 
174 /// ContainsLabel - Return true if the statement contains a label in it.  If
175 /// this statement is not executed normally, it not containing a label means
176 /// that we can just remove the code.
177 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
178   // Null statement, not a label!
179   if (S == 0) return false;
180 
181   // If this is a label, we have to emit the code, consider something like:
182   // if (0) {  ...  foo:  bar(); }  goto foo;
183   if (isa<LabelStmt>(S))
184     return true;
185 
186   // If this is a case/default statement, and we haven't seen a switch, we have
187   // to emit the code.
188   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
189     return true;
190 
191   // If this is a switch statement, we want to ignore cases below it.
192   if (isa<SwitchStmt>(S))
193     IgnoreCaseStmts = true;
194 
195   // Scan subexpressions for verboten labels.
196   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
197        I != E; ++I)
198     if (ContainsLabel(*I, IgnoreCaseStmts))
199       return true;
200 
201   return false;
202 }
203 
204 
205 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
206 /// a constant, or if it does but contains a label, return 0.  If it constant
207 /// folds to 'true' and does not contain a label, return 1, if it constant folds
208 /// to 'false' and does not contain a label, return -1.
209 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
210   // FIXME: Rename and handle conversion of other evaluatable things
211   // to bool.
212   Expr::EvalResult Result;
213   if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
214       Result.HasSideEffects)
215     return 0;  // Not foldable, not integer or not fully evaluatable.
216 
217   if (CodeGenFunction::ContainsLabel(Cond))
218     return 0;  // Contains a label.
219 
220   return Result.Val.getInt().getBoolValue() ? 1 : -1;
221 }
222 
223 
224 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
225 /// statement) to the specified blocks.  Based on the condition, this might try
226 /// to simplify the codegen of the conditional based on the branch.
227 ///
228 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
229                                            llvm::BasicBlock *TrueBlock,
230                                            llvm::BasicBlock *FalseBlock) {
231   if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
232     return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
233 
234   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
235     // Handle X && Y in a condition.
236     if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
237       // If we have "1 && X", simplify the code.  "0 && X" would have constant
238       // folded if the case was simple enough.
239       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
240         // br(1 && X) -> br(X).
241         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
242       }
243 
244       // If we have "X && 1", simplify the code to use an uncond branch.
245       // "X && 0" would have been constant folded to 0.
246       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
247         // br(X && 1) -> br(X).
248         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
249       }
250 
251       // Emit the LHS as a conditional.  If the LHS conditional is false, we
252       // want to jump to the FalseBlock.
253       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
254       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
255       EmitBlock(LHSTrue);
256 
257       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
258       return;
259     } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
260       // If we have "0 || X", simplify the code.  "1 || X" would have constant
261       // folded if the case was simple enough.
262       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
263         // br(0 || X) -> br(X).
264         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
265       }
266 
267       // If we have "X || 0", simplify the code to use an uncond branch.
268       // "X || 1" would have been constant folded to 1.
269       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
270         // br(X || 0) -> br(X).
271         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
272       }
273 
274       // Emit the LHS as a conditional.  If the LHS conditional is true, we
275       // want to jump to the TrueBlock.
276       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
277       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
278       EmitBlock(LHSFalse);
279 
280       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
281       return;
282     }
283   }
284 
285   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
286     // br(!x, t, f) -> br(x, f, t)
287     if (CondUOp->getOpcode() == UnaryOperator::LNot)
288       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
289   }
290 
291   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
292     // Handle ?: operator.
293 
294     // Just ignore GNU ?: extension.
295     if (CondOp->getLHS()) {
296       // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
297       llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
298       llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
299       EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
300       EmitBlock(LHSBlock);
301       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
302       EmitBlock(RHSBlock);
303       EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
304       return;
305     }
306   }
307 
308   // Emit the code with the fully general case.
309   llvm::Value *CondV = EvaluateExprAsBool(Cond);
310   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
311 }
312 
313 /// getCGRecordLayout - Return record layout info.
314 const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
315                                                          QualType Ty) {
316   const RecordType *RTy = Ty->getAsRecordType();
317   assert (RTy && "Unexpected type. RecordType expected here.");
318 
319   return CGT.getCGRecordLayout(RTy->getDecl());
320 }
321 
322 /// ErrorUnsupported - Print out an error that codegen doesn't support the
323 /// specified stmt yet.
324 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
325                                        bool OmitOnError) {
326   CGM.ErrorUnsupported(S, Type, OmitOnError);
327 }
328 
329 unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
330   // Use LabelIDs.size() as the new ID if one hasn't been assigned.
331   return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
332 }
333 
334 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty)
335 {
336   const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
337   if (DestPtr->getType() != BP)
338     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
339 
340   // Get size and alignment info for this aggregate.
341   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
342 
343   // FIXME: Handle variable sized types.
344   const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
345 
346   Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
347                       llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
348                       // TypeInfo.first describes size in bits.
349                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
350                       llvm::ConstantInt::get(llvm::Type::Int32Ty,
351                                              TypeInfo.second/8));
352 }
353 
354 void CodeGenFunction::EmitIndirectSwitches() {
355   llvm::BasicBlock *Default;
356 
357   if (IndirectSwitches.empty())
358     return;
359 
360   if (!LabelIDs.empty()) {
361     Default = getBasicBlockForLabel(LabelIDs.begin()->first);
362   } else {
363     // No possible targets for indirect goto, just emit an infinite
364     // loop.
365     Default = createBasicBlock("indirectgoto.loop", CurFn);
366     llvm::BranchInst::Create(Default, Default);
367   }
368 
369   for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
370          e = IndirectSwitches.end(); i != e; ++i) {
371     llvm::SwitchInst *I = *i;
372 
373     I->setSuccessor(0, Default);
374     for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
375            LE = LabelIDs.end(); LI != LE; ++LI) {
376       I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
377                                         LI->second),
378                  getBasicBlockForLabel(LI->first));
379     }
380   }
381 }
382 
383 llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty)
384 {
385   // FIXME: This entire method is hardcoded for 32-bit X86.
386 
387   const char *TargetPrefix = getContext().Target.getTargetPrefix();
388 
389   if (strcmp(TargetPrefix, "x86") != 0 ||
390       getContext().Target.getPointerWidth(0) != 32)
391     return 0;
392 
393   const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
394   const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
395 
396   llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
397                                                        "ap");
398   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
399   llvm::Value *AddrTyped =
400     Builder.CreateBitCast(Addr,
401                           llvm::PointerType::getUnqual(ConvertType(Ty)));
402 
403   uint64_t SizeInBytes = getContext().getTypeSize(Ty) / 8;
404   const unsigned ArgumentSizeInBytes = 4;
405   if (SizeInBytes < ArgumentSizeInBytes)
406     SizeInBytes = ArgumentSizeInBytes;
407 
408   llvm::Value *NextAddr =
409     Builder.CreateGEP(Addr,
410                       llvm::ConstantInt::get(llvm::Type::Int32Ty, SizeInBytes),
411                       "ap.next");
412   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
413 
414   return AddrTyped;
415 }
416 
417 
418 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT)
419 {
420   llvm::Value *&SizeEntry = VLASizeMap[VAT];
421 
422   assert(SizeEntry && "Did not emit size for type");
423   return SizeEntry;
424 }
425 
426 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty)
427 {
428   assert(Ty->isVariablyModifiedType() &&
429          "Must pass variably modified type to EmitVLASizes!");
430 
431   if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
432     llvm::Value *&SizeEntry = VLASizeMap[VAT];
433 
434     if (!SizeEntry) {
435       // Get the element size;
436       llvm::Value *ElemSize;
437 
438       QualType ElemTy = VAT->getElementType();
439 
440       if (ElemTy->isVariableArrayType())
441         ElemSize = EmitVLASize(ElemTy);
442       else {
443         // FIXME: We use Int32Ty here because the alloca instruction takes a
444         // 32-bit integer. What should we do about overflow?
445         ElemSize = llvm::ConstantInt::get(llvm::Type::Int32Ty,
446                                           getContext().getTypeSize(ElemTy) / 8);
447       }
448 
449       llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
450 
451       SizeEntry = Builder.CreateMul(ElemSize, NumElements);
452     }
453 
454     return SizeEntry;
455   } else if (const PointerType *PT = Ty->getAsPointerType())
456     EmitVLASize(PT->getPointeeType());
457   else {
458     assert(0 && "unknown VM type!");
459   }
460 
461   return 0;
462 }
463