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