1193326Sed//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed// This coordinates the per-function state used while generating code.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14193326Sed#include "CodeGenFunction.h"
15226633Sdim#include "CGCUDARuntime.h"
16212904Sdim#include "CGCXXABI.h"
17193326Sed#include "CGDebugInfo.h"
18249423Sdim#include "CodeGenModule.h"
19263508Sdim#include "TargetInfo.h"
20193326Sed#include "clang/AST/ASTContext.h"
21193326Sed#include "clang/AST/Decl.h"
22193326Sed#include "clang/AST/DeclCXX.h"
23200583Srdivacky#include "clang/AST/StmtCXX.h"
24249423Sdim#include "clang/Basic/OpenCL.h"
25249423Sdim#include "clang/Basic/TargetInfo.h"
26263508Sdim#include "clang/CodeGen/CGFunctionInfo.h"
27210299Sed#include "clang/Frontend/CodeGenOptions.h"
28249423Sdim#include "llvm/IR/DataLayout.h"
29249423Sdim#include "llvm/IR/Intrinsics.h"
30249423Sdim#include "llvm/IR/MDBuilder.h"
31249423Sdim#include "llvm/IR/Operator.h"
32193326Sedusing namespace clang;
33193326Sedusing namespace CodeGen;
34193326Sed
35239462SdimCodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
36263508Sdim    : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
37263508Sdim      Builder(cgm.getModule().getContext()), CapturedStmtInfo(0),
38263508Sdim      SanitizePerformTypeCheck(CGM.getSanOpts().Null |
39263508Sdim                               CGM.getSanOpts().Alignment |
40263508Sdim                               CGM.getSanOpts().ObjectSize |
41263508Sdim                               CGM.getSanOpts().Vptr),
42263508Sdim      SanOpts(&CGM.getSanOpts()), AutoreleaseResult(false), BlockInfo(0),
43263508Sdim      BlockPointer(0), LambdaThisCaptureField(0), NormalCleanupDest(0),
44263508Sdim      NextCleanupDestIndex(1), FirstBlockInfo(0), EHResumeBlock(0),
45263508Sdim      ExceptionSlot(0), EHSelectorSlot(0), DebugInfo(CGM.getModuleDebugInfo()),
46263508Sdim      DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(0),
47263508Sdim      SwitchInsn(0), CaseRangeBlock(0), UnreachableBlock(0), NumReturnExprs(0),
48263508Sdim      NumSimpleReturnExprs(0), CXXABIThisDecl(0), CXXABIThisValue(0),
49263508Sdim      CXXThisValue(0), CXXDefaultInitExprThis(0),
50263508Sdim      CXXStructorImplicitParamDecl(0), CXXStructorImplicitParamValue(0),
51263508Sdim      OutermostConditional(0), CurLexicalScope(0), TerminateLandingPad(0),
52263508Sdim      TerminateHandler(0), TrapBB(0) {
53239462Sdim  if (!suppressNewContext)
54239462Sdim    CGM.getCXXABI().getMangleContext().startNewFunction();
55249423Sdim
56249423Sdim  llvm::FastMathFlags FMF;
57249423Sdim  if (CGM.getLangOpts().FastMath)
58249423Sdim    FMF.setUnsafeAlgebra();
59249423Sdim  if (CGM.getLangOpts().FiniteMathOnly) {
60249423Sdim    FMF.setNoNaNs();
61249423Sdim    FMF.setNoInfs();
62249423Sdim  }
63249423Sdim  Builder.SetFastMathFlags(FMF);
64193326Sed}
65193326Sed
66234353SdimCodeGenFunction::~CodeGenFunction() {
67263508Sdim  assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
68263508Sdim
69234353Sdim  // If there are any unclaimed block infos, go ahead and destroy them
70234353Sdim  // now.  This can happen if IR-gen gets clever and skips evaluating
71234353Sdim  // something.
72234353Sdim  if (FirstBlockInfo)
73234353Sdim    destroyBlockInfos(FirstBlockInfo);
74234353Sdim}
75193326Sed
76234353Sdim
77224145Sdimllvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
78193326Sed  return CGM.getTypes().ConvertTypeForMem(T);
79193326Sed}
80193326Sed
81224145Sdimllvm::Type *CodeGenFunction::ConvertType(QualType T) {
82193326Sed  return CGM.getTypes().ConvertType(T);
83193326Sed}
84193326Sed
85249423SdimTypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
86249423Sdim  type = type.getCanonicalType();
87249423Sdim  while (true) {
88249423Sdim    switch (type->getTypeClass()) {
89223017Sdim#define TYPE(name, parent)
90223017Sdim#define ABSTRACT_TYPE(name, parent)
91223017Sdim#define NON_CANONICAL_TYPE(name, parent) case Type::name:
92223017Sdim#define DEPENDENT_TYPE(name, parent) case Type::name:
93223017Sdim#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
94223017Sdim#include "clang/AST/TypeNodes.def"
95249423Sdim      llvm_unreachable("non-canonical or dependent type in IR-generation");
96223017Sdim
97251662Sdim    case Type::Auto:
98251662Sdim      llvm_unreachable("undeduced auto type in IR-generation");
99251662Sdim
100249423Sdim    // Various scalar types.
101249423Sdim    case Type::Builtin:
102249423Sdim    case Type::Pointer:
103249423Sdim    case Type::BlockPointer:
104249423Sdim    case Type::LValueReference:
105249423Sdim    case Type::RValueReference:
106249423Sdim    case Type::MemberPointer:
107249423Sdim    case Type::Vector:
108249423Sdim    case Type::ExtVector:
109249423Sdim    case Type::FunctionProto:
110249423Sdim    case Type::FunctionNoProto:
111249423Sdim    case Type::Enum:
112249423Sdim    case Type::ObjCObjectPointer:
113249423Sdim      return TEK_Scalar;
114223017Sdim
115249423Sdim    // Complexes.
116249423Sdim    case Type::Complex:
117249423Sdim      return TEK_Complex;
118226633Sdim
119249423Sdim    // Arrays, records, and Objective-C objects.
120249423Sdim    case Type::ConstantArray:
121249423Sdim    case Type::IncompleteArray:
122249423Sdim    case Type::VariableArray:
123249423Sdim    case Type::Record:
124249423Sdim    case Type::ObjCObject:
125249423Sdim    case Type::ObjCInterface:
126249423Sdim      return TEK_Aggregate;
127249423Sdim
128249423Sdim    // We operate on atomic values according to their underlying type.
129249423Sdim    case Type::Atomic:
130249423Sdim      type = cast<AtomicType>(type)->getValueType();
131249423Sdim      continue;
132249423Sdim    }
133249423Sdim    llvm_unreachable("unknown type kind!");
134223017Sdim  }
135193326Sed}
136193326Sed
137193326Sedvoid CodeGenFunction::EmitReturnBlock() {
138193326Sed  // For cleanliness, we try to avoid emitting the return block for
139193326Sed  // simple cases.
140193326Sed  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
141193326Sed
142193326Sed  if (CurBB) {
143193326Sed    assert(!CurBB->getTerminator() && "Unexpected terminated block.");
144193326Sed
145198092Srdivacky    // We have a valid insert point, reuse it if it is empty or there are no
146198092Srdivacky    // explicit jumps to the return block.
147212904Sdim    if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
148212904Sdim      ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
149212904Sdim      delete ReturnBlock.getBlock();
150198092Srdivacky    } else
151212904Sdim      EmitBlock(ReturnBlock.getBlock());
152193326Sed    return;
153193326Sed  }
154193326Sed
155193326Sed  // Otherwise, if the return block is the target of a single direct
156193326Sed  // branch then we can just put the code in that block instead. This
157193326Sed  // cleans up functions which started with a unified return block.
158212904Sdim  if (ReturnBlock.getBlock()->hasOneUse()) {
159198092Srdivacky    llvm::BranchInst *BI =
160212904Sdim      dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin());
161210299Sed    if (BI && BI->isUnconditional() &&
162212904Sdim        BI->getSuccessor(0) == ReturnBlock.getBlock()) {
163249423Sdim      // Reset insertion point, including debug location, and delete the
164249423Sdim      // branch.  This is really subtle and only works because the next change
165249423Sdim      // in location will hit the caching in CGDebugInfo::EmitLocation and not
166249423Sdim      // override this.
167226633Sdim      Builder.SetCurrentDebugLocation(BI->getDebugLoc());
168193326Sed      Builder.SetInsertPoint(BI->getParent());
169193326Sed      BI->eraseFromParent();
170212904Sdim      delete ReturnBlock.getBlock();
171193326Sed      return;
172193326Sed    }
173193326Sed  }
174193326Sed
175193326Sed  // FIXME: We are at an unreachable point, there is no reason to emit the block
176193326Sed  // unless it has uses. However, we still need a place to put the debug
177193326Sed  // region.end for now.
178193326Sed
179212904Sdim  EmitBlock(ReturnBlock.getBlock());
180193326Sed}
181193326Sed
182210299Sedstatic void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
183210299Sed  if (!BB) return;
184210299Sed  if (!BB->use_empty())
185210299Sed    return CGF.CurFn->getBasicBlockList().push_back(BB);
186210299Sed  delete BB;
187210299Sed}
188210299Sed
189193326Sedvoid CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
190193326Sed  assert(BreakContinueStack.empty() &&
191193326Sed         "mismatched push/pop in break/continue stack!");
192198092Srdivacky
193251662Sdim  bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
194263508Sdim    && NumSimpleReturnExprs == NumReturnExprs
195263508Sdim    && ReturnBlock.getBlock()->use_empty();
196263508Sdim  // Usually the return expression is evaluated before the cleanup
197263508Sdim  // code.  If the function contains only a simple return statement,
198263508Sdim  // such as a constant, the location before the cleanup code becomes
199263508Sdim  // the last useful breakpoint in the function, because the simple
200263508Sdim  // return expression will be evaluated after the cleanup code. To be
201263508Sdim  // safe, set the debug location for cleanup code to the location of
202263508Sdim  // the return statement.  Otherwise the cleanup code should be at the
203263508Sdim  // end of the function's lexical scope.
204263508Sdim  //
205263508Sdim  // If there are multiple branches to the return block, the branch
206263508Sdim  // instructions will get the location of the return statements and
207263508Sdim  // all will be fine.
208251662Sdim  if (CGDebugInfo *DI = getDebugInfo()) {
209251662Sdim    if (OnlySimpleReturnStmts)
210263508Sdim      DI->EmitLocation(Builder, LastStopPoint);
211251662Sdim    else
212251662Sdim      DI->EmitLocation(Builder, EndLoc);
213251662Sdim  }
214249423Sdim
215224145Sdim  // Pop any cleanups that might have been associated with the
216224145Sdim  // parameters.  Do this in whatever block we're currently in; it's
217224145Sdim  // important to do this before we enter the return block or return
218224145Sdim  // edges will be *really* confused.
219251662Sdim  bool EmitRetDbgLoc = true;
220251662Sdim  if (EHStack.stable_begin() != PrologueCleanupDepth) {
221263508Sdim    PopCleanupBlocks(PrologueCleanupDepth);
222224145Sdim
223251662Sdim    // Make sure the line table doesn't jump back into the body for
224251662Sdim    // the ret after it's been at EndLoc.
225251662Sdim    EmitRetDbgLoc = false;
226251662Sdim
227251662Sdim    if (CGDebugInfo *DI = getDebugInfo())
228251662Sdim      if (OnlySimpleReturnStmts)
229251662Sdim        DI->EmitLocation(Builder, EndLoc);
230251662Sdim  }
231251662Sdim
232198092Srdivacky  // Emit function epilog (to return).
233193326Sed  EmitReturnBlock();
234193326Sed
235218893Sdim  if (ShouldInstrumentFunction())
236218893Sdim    EmitFunctionInstrumentation("__cyg_profile_func_exit");
237210299Sed
238193326Sed  // Emit debug descriptor for function end.
239193326Sed  if (CGDebugInfo *DI = getDebugInfo()) {
240212904Sdim    DI->EmitFunctionEnd(Builder);
241193326Sed  }
242193326Sed
243263508Sdim  EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
244200583Srdivacky  EmitEndEHSpec(CurCodeDecl);
245193326Sed
246210299Sed  assert(EHStack.empty() &&
247210299Sed         "did not remove all scopes from cleanup stack!");
248210299Sed
249198893Srdivacky  // If someone did an indirect goto, emit the indirect goto block at the end of
250198893Srdivacky  // the function.
251198893Srdivacky  if (IndirectBranch) {
252198893Srdivacky    EmitBlock(IndirectBranch->getParent());
253198893Srdivacky    Builder.ClearInsertionPoint();
254198893Srdivacky  }
255249423Sdim
256193326Sed  // Remove the AllocaInsertPt instruction, which is just a convenience for us.
257193326Sed  llvm::Instruction *Ptr = AllocaInsertPt;
258193326Sed  AllocaInsertPt = 0;
259193326Sed  Ptr->eraseFromParent();
260249423Sdim
261198893Srdivacky  // If someone took the address of a label but never did an indirect goto, we
262198893Srdivacky  // made a zero entry PHI node, which is illegal, zap it now.
263198893Srdivacky  if (IndirectBranch) {
264198893Srdivacky    llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
265198893Srdivacky    if (PN->getNumIncomingValues() == 0) {
266198893Srdivacky      PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
267198893Srdivacky      PN->eraseFromParent();
268198893Srdivacky    }
269198893Srdivacky  }
270210299Sed
271226633Sdim  EmitIfUsed(*this, EHResumeBlock);
272210299Sed  EmitIfUsed(*this, TerminateLandingPad);
273210299Sed  EmitIfUsed(*this, TerminateHandler);
274210299Sed  EmitIfUsed(*this, UnreachableBlock);
275210299Sed
276210299Sed  if (CGM.getCodeGenOpts().EmitDeclMetadata)
277210299Sed    EmitDeclMetadata();
278193326Sed}
279193326Sed
280210299Sed/// ShouldInstrumentFunction - Return true if the current function should be
281210299Sed/// instrumented with __cyg_profile_func_* calls
282210299Sedbool CodeGenFunction::ShouldInstrumentFunction() {
283210299Sed  if (!CGM.getCodeGenOpts().InstrumentFunctions)
284210299Sed    return false;
285223017Sdim  if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
286210299Sed    return false;
287210299Sed  return true;
288210299Sed}
289210299Sed
290210299Sed/// EmitFunctionInstrumentation - Emit LLVM code to call the specified
291210299Sed/// instrumentation function with the current function and the call site, if
292210299Sed/// function instrumentation is enabled.
293210299Sedvoid CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
294210299Sed  // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
295224145Sdim  llvm::PointerType *PointerTy = Int8PtrTy;
296224145Sdim  llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
297226633Sdim  llvm::FunctionType *FunctionTy =
298234353Sdim    llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
299210299Sed
300210299Sed  llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
301210299Sed  llvm::CallInst *CallSite = Builder.CreateCall(
302224145Sdim    CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
303210299Sed    llvm::ConstantInt::get(Int32Ty, 0),
304210299Sed    "callsite");
305210299Sed
306249423Sdim  llvm::Value *args[] = {
307249423Sdim    llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
308249423Sdim    CallSite
309249423Sdim  };
310249423Sdim
311249423Sdim  EmitNounwindRuntimeCall(F, args);
312210299Sed}
313210299Sed
314218893Sdimvoid CodeGenFunction::EmitMCountInstrumentation() {
315234353Sdim  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
316218893Sdim
317251662Sdim  llvm::Constant *MCountFn =
318251662Sdim    CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName());
319249423Sdim  EmitNounwindRuntimeCall(MCountFn);
320218893Sdim}
321218893Sdim
322239462Sdim// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
323239462Sdim// information in the program executable. The argument information stored
324239462Sdim// includes the argument name, its type, the address and access qualifiers used.
325239462Sdimstatic void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
326239462Sdim                                 CodeGenModule &CGM,llvm::LLVMContext &Context,
327249423Sdim                                 SmallVector <llvm::Value*, 5> &kernelMDArgs,
328249423Sdim                                 CGBuilderTy& Builder, ASTContext &ASTCtx) {
329249423Sdim  // Create MDNodes that represent the kernel arg metadata.
330239462Sdim  // Each MDNode is a list in the form of "key", N number of values which is
331239462Sdim  // the same number of values as their are kernel arguments.
332249423Sdim
333249423Sdim  // MDNode for the kernel argument address space qualifiers.
334249423Sdim  SmallVector<llvm::Value*, 8> addressQuals;
335249423Sdim  addressQuals.push_back(llvm::MDString::get(Context, "kernel_arg_addr_space"));
336249423Sdim
337249423Sdim  // MDNode for the kernel argument access qualifiers (images only).
338249423Sdim  SmallVector<llvm::Value*, 8> accessQuals;
339249423Sdim  accessQuals.push_back(llvm::MDString::get(Context, "kernel_arg_access_qual"));
340249423Sdim
341249423Sdim  // MDNode for the kernel argument type names.
342249423Sdim  SmallVector<llvm::Value*, 8> argTypeNames;
343249423Sdim  argTypeNames.push_back(llvm::MDString::get(Context, "kernel_arg_type"));
344249423Sdim
345249423Sdim  // MDNode for the kernel argument type qualifiers.
346249423Sdim  SmallVector<llvm::Value*, 8> argTypeQuals;
347249423Sdim  argTypeQuals.push_back(llvm::MDString::get(Context, "kernel_arg_type_qual"));
348249423Sdim
349239462Sdim  // MDNode for the kernel argument names.
350239462Sdim  SmallVector<llvm::Value*, 8> argNames;
351239462Sdim  argNames.push_back(llvm::MDString::get(Context, "kernel_arg_name"));
352249423Sdim
353239462Sdim  for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
354239462Sdim    const ParmVarDecl *parm = FD->getParamDecl(i);
355249423Sdim    QualType ty = parm->getType();
356249423Sdim    std::string typeQuals;
357249423Sdim
358249423Sdim    if (ty->isPointerType()) {
359249423Sdim      QualType pointeeTy = ty->getPointeeType();
360249423Sdim
361249423Sdim      // Get address qualifier.
362249423Sdim      addressQuals.push_back(Builder.getInt32(ASTCtx.getTargetAddressSpace(
363249423Sdim        pointeeTy.getAddressSpace())));
364249423Sdim
365249423Sdim      // Get argument type name.
366249423Sdim      std::string typeName = pointeeTy.getUnqualifiedType().getAsString() + "*";
367249423Sdim
368249423Sdim      // Turn "unsigned type" to "utype"
369249423Sdim      std::string::size_type pos = typeName.find("unsigned");
370249423Sdim      if (pos != std::string::npos)
371249423Sdim        typeName.erase(pos+1, 8);
372249423Sdim
373249423Sdim      argTypeNames.push_back(llvm::MDString::get(Context, typeName));
374249423Sdim
375249423Sdim      // Get argument type qualifiers:
376249423Sdim      if (ty.isRestrictQualified())
377249423Sdim        typeQuals = "restrict";
378249423Sdim      if (pointeeTy.isConstQualified() ||
379249423Sdim          (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
380249423Sdim        typeQuals += typeQuals.empty() ? "const" : " const";
381249423Sdim      if (pointeeTy.isVolatileQualified())
382249423Sdim        typeQuals += typeQuals.empty() ? "volatile" : " volatile";
383249423Sdim    } else {
384249423Sdim      addressQuals.push_back(Builder.getInt32(0));
385249423Sdim
386249423Sdim      // Get argument type name.
387249423Sdim      std::string typeName = ty.getUnqualifiedType().getAsString();
388249423Sdim
389249423Sdim      // Turn "unsigned type" to "utype"
390249423Sdim      std::string::size_type pos = typeName.find("unsigned");
391249423Sdim      if (pos != std::string::npos)
392249423Sdim        typeName.erase(pos+1, 8);
393249423Sdim
394249423Sdim      argTypeNames.push_back(llvm::MDString::get(Context, typeName));
395249423Sdim
396249423Sdim      // Get argument type qualifiers:
397249423Sdim      if (ty.isConstQualified())
398249423Sdim        typeQuals = "const";
399249423Sdim      if (ty.isVolatileQualified())
400249423Sdim        typeQuals += typeQuals.empty() ? "volatile" : " volatile";
401249423Sdim    }
402239462Sdim
403249423Sdim    argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
404249423Sdim
405249423Sdim    // Get image access qualifier:
406249423Sdim    if (ty->isImageType()) {
407249423Sdim      if (parm->hasAttr<OpenCLImageAccessAttr>() &&
408249423Sdim          parm->getAttr<OpenCLImageAccessAttr>()->getAccess() == CLIA_write_only)
409249423Sdim        accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
410249423Sdim      else
411249423Sdim        accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
412249423Sdim    } else
413249423Sdim      accessQuals.push_back(llvm::MDString::get(Context, "none"));
414249423Sdim
415239462Sdim    // Get argument name.
416239462Sdim    argNames.push_back(llvm::MDString::get(Context, parm->getName()));
417239462Sdim  }
418249423Sdim
419249423Sdim  kernelMDArgs.push_back(llvm::MDNode::get(Context, addressQuals));
420249423Sdim  kernelMDArgs.push_back(llvm::MDNode::get(Context, accessQuals));
421249423Sdim  kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeNames));
422249423Sdim  kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeQuals));
423239462Sdim  kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames));
424239462Sdim}
425239462Sdim
426249423Sdimvoid CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
427239462Sdim                                               llvm::Function *Fn)
428239462Sdim{
429239462Sdim  if (!FD->hasAttr<OpenCLKernelAttr>())
430239462Sdim    return;
431239462Sdim
432239462Sdim  llvm::LLVMContext &Context = getLLVMContext();
433239462Sdim
434249423Sdim  SmallVector <llvm::Value*, 5> kernelMDArgs;
435239462Sdim  kernelMDArgs.push_back(Fn);
436239462Sdim
437239462Sdim  if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
438249423Sdim    GenOpenCLArgMetadata(FD, Fn, CGM, Context, kernelMDArgs,
439249423Sdim                         Builder, getContext());
440249423Sdim
441249423Sdim  if (FD->hasAttr<VecTypeHintAttr>()) {
442249423Sdim    VecTypeHintAttr *attr = FD->getAttr<VecTypeHintAttr>();
443249423Sdim    QualType hintQTy = attr->getTypeHint();
444249423Sdim    const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
445249423Sdim    bool isSignedInteger =
446249423Sdim        hintQTy->isSignedIntegerType() ||
447249423Sdim        (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
448249423Sdim    llvm::Value *attrMDArgs[] = {
449249423Sdim      llvm::MDString::get(Context, "vec_type_hint"),
450249423Sdim      llvm::UndefValue::get(CGM.getTypes().ConvertType(attr->getTypeHint())),
451249423Sdim      llvm::ConstantInt::get(
452249423Sdim          llvm::IntegerType::get(Context, 32),
453249423Sdim          llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0)))
454249423Sdim    };
455249423Sdim    kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
456249423Sdim  }
457249423Sdim
458239462Sdim  if (FD->hasAttr<WorkGroupSizeHintAttr>()) {
459239462Sdim    WorkGroupSizeHintAttr *attr = FD->getAttr<WorkGroupSizeHintAttr>();
460249423Sdim    llvm::Value *attrMDArgs[] = {
461249423Sdim      llvm::MDString::get(Context, "work_group_size_hint"),
462249423Sdim      Builder.getInt32(attr->getXDim()),
463249423Sdim      Builder.getInt32(attr->getYDim()),
464249423Sdim      Builder.getInt32(attr->getZDim())
465249423Sdim    };
466239462Sdim    kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
467239462Sdim  }
468239462Sdim
469239462Sdim  if (FD->hasAttr<ReqdWorkGroupSizeAttr>()) {
470239462Sdim    ReqdWorkGroupSizeAttr *attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
471249423Sdim    llvm::Value *attrMDArgs[] = {
472249423Sdim      llvm::MDString::get(Context, "reqd_work_group_size"),
473249423Sdim      Builder.getInt32(attr->getXDim()),
474249423Sdim      Builder.getInt32(attr->getYDim()),
475249423Sdim      Builder.getInt32(attr->getZDim())
476249423Sdim    };
477239462Sdim    kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
478239462Sdim  }
479239462Sdim
480239462Sdim  llvm::MDNode *kernelMDNode = llvm::MDNode::get(Context, kernelMDArgs);
481239462Sdim  llvm::NamedMDNode *OpenCLKernelMetadata =
482239462Sdim    CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
483239462Sdim  OpenCLKernelMetadata->addOperand(kernelMDNode);
484239462Sdim}
485239462Sdim
486251662Sdimvoid CodeGenFunction::StartFunction(GlobalDecl GD,
487251662Sdim                                    QualType RetTy,
488193326Sed                                    llvm::Function *Fn,
489221345Sdim                                    const CGFunctionInfo &FnInfo,
490193326Sed                                    const FunctionArgList &Args,
491193326Sed                                    SourceLocation StartLoc) {
492198092Srdivacky  const Decl *D = GD.getDecl();
493249423Sdim
494193326Sed  DidCallStackSave = false;
495251662Sdim  CurCodeDecl = D;
496251662Sdim  CurFuncDecl = (D ? D->getNonClosureContext() : 0);
497193326Sed  FnRetTy = RetTy;
498193326Sed  CurFn = Fn;
499221345Sdim  CurFnInfo = &FnInfo;
500193326Sed  assert(CurFn->isDeclaration() && "Function already has body?");
501193326Sed
502249423Sdim  if (CGM.getSanitizerBlacklist().isIn(*Fn)) {
503249423Sdim    SanOpts = &SanitizerOptions::Disabled;
504249423Sdim    SanitizePerformTypeCheck = false;
505249423Sdim  }
506249423Sdim
507203955Srdivacky  // Pass inline keyword to optimizer if it appears explicitly on any
508203955Srdivacky  // declaration.
509249423Sdim  if (!CGM.getCodeGenOpts().NoInline)
510234353Sdim    if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
511234353Sdim      for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
512234353Sdim             RE = FD->redecls_end(); RI != RE; ++RI)
513234353Sdim        if (RI->isInlineSpecified()) {
514249423Sdim          Fn->addFnAttr(llvm::Attribute::InlineHint);
515234353Sdim          break;
516234353Sdim        }
517203955Srdivacky
518243830Sdim  if (getLangOpts().OpenCL) {
519218893Sdim    // Add metadata for a kernel function.
520218893Sdim    if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
521239462Sdim      EmitOpenCLKernelMetadata(FD, Fn);
522218893Sdim  }
523218893Sdim
524263508Sdim  // If we are checking function types, emit a function type signature as
525263508Sdim  // prefix data.
526263508Sdim  if (getLangOpts().CPlusPlus && SanOpts->Function) {
527263508Sdim    if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
528263508Sdim      if (llvm::Constant *PrefixSig =
529263508Sdim              CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
530263508Sdim        llvm::Constant *FTRTTIConst =
531263508Sdim            CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
532263508Sdim        llvm::Constant *PrefixStructElems[] = { PrefixSig, FTRTTIConst };
533263508Sdim        llvm::Constant *PrefixStructConst =
534263508Sdim            llvm::ConstantStruct::getAnon(PrefixStructElems, /*Packed=*/true);
535263508Sdim        Fn->setPrefixData(PrefixStructConst);
536263508Sdim      }
537263508Sdim    }
538263508Sdim  }
539263508Sdim
540193326Sed  llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
541193326Sed
542193326Sed  // Create a marker to make it easy to insert allocas into the entryblock
543193326Sed  // later.  Don't create this with the builder, because we don't want it
544193326Sed  // folded.
545210299Sed  llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
546210299Sed  AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
547193326Sed  if (Builder.isNamePreserving())
548193326Sed    AllocaInsertPt->setName("allocapt");
549198092Srdivacky
550210299Sed  ReturnBlock = getJumpDestInCurrentScope("return");
551198092Srdivacky
552193326Sed  Builder.SetInsertPoint(EntryBB);
553198092Srdivacky
554193326Sed  // Emit subprogram debug descriptor.
555193326Sed  if (CGDebugInfo *DI = getDebugInfo()) {
556249423Sdim    SmallVector<QualType, 16> ArgTypes;
557234353Sdim    for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
558234353Sdim	 i != e; ++i) {
559249423Sdim      ArgTypes.push_back((*i)->getType());
560234353Sdim    }
561234353Sdim
562218893Sdim    QualType FnType =
563249423Sdim      getContext().getFunctionType(RetTy, ArgTypes,
564218893Sdim                                   FunctionProtoType::ExtProtoInfo());
565218893Sdim
566193326Sed    DI->setLocation(StartLoc);
567202379Srdivacky    DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
568193326Sed  }
569193326Sed
570218893Sdim  if (ShouldInstrumentFunction())
571218893Sdim    EmitFunctionInstrumentation("__cyg_profile_func_enter");
572210299Sed
573218893Sdim  if (CGM.getCodeGenOpts().InstrumentForProfiling)
574218893Sdim    EmitMCountInstrumentation();
575218893Sdim
576200583Srdivacky  if (RetTy->isVoidType()) {
577200583Srdivacky    // Void type; nothing to return.
578200583Srdivacky    ReturnValue = 0;
579200583Srdivacky  } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
580249423Sdim             !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
581200583Srdivacky    // Indirect aggregate return; emit returned value directly into sret slot.
582204643Srdivacky    // This reduces code size, and affects correctness in C++.
583200583Srdivacky    ReturnValue = CurFn->arg_begin();
584200583Srdivacky  } else {
585204643Srdivacky    ReturnValue = CreateIRTemp(RetTy, "retval");
586224145Sdim
587224145Sdim    // Tell the epilog emitter to autorelease the result.  We do this
588224145Sdim    // now so that various specialized functions can suppress it
589224145Sdim    // during their IR-generation.
590234353Sdim    if (getLangOpts().ObjCAutoRefCount &&
591224145Sdim        !CurFnInfo->isReturnsRetained() &&
592224145Sdim        RetTy->isObjCRetainableType())
593224145Sdim      AutoreleaseResult = true;
594200583Srdivacky  }
595200583Srdivacky
596200583Srdivacky  EmitStartEHSpec(CurCodeDecl);
597224145Sdim
598224145Sdim  PrologueCleanupDepth = EHStack.stable_begin();
599193326Sed  EmitFunctionProlog(*CurFnInfo, CurFn, Args);
600198092Srdivacky
601234353Sdim  if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
602212904Sdim    CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
603234353Sdim    const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
604234353Sdim    if (MD->getParent()->isLambda() &&
605234353Sdim        MD->getOverloadedOperator() == OO_Call) {
606234353Sdim      // We're in a lambda; figure out the captures.
607234353Sdim      MD->getParent()->getCaptureFields(LambdaCaptureFields,
608234353Sdim                                        LambdaThisCaptureField);
609234353Sdim      if (LambdaThisCaptureField) {
610234353Sdim        // If this lambda captures this, load it.
611251662Sdim        LValue ThisLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
612263508Sdim        CXXThisValue = EmitLoadOfLValue(ThisLValue,
613263508Sdim                                        SourceLocation()).getScalarVal();
614234353Sdim      }
615234353Sdim    } else {
616234353Sdim      // Not in a lambda; just use 'this' from the method.
617234353Sdim      // FIXME: Should we generate a new load for each use of 'this'?  The
618234353Sdim      // fast register allocator would be happier...
619234353Sdim      CXXThisValue = CXXABIThisValue;
620234353Sdim    }
621234353Sdim  }
622204643Srdivacky
623193326Sed  // If any of the arguments have a variably modified type, make sure to
624193326Sed  // emit the type size.
625193326Sed  for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
626193326Sed       i != e; ++i) {
627249423Sdim    const VarDecl *VD = *i;
628193326Sed
629249423Sdim    // Dig out the type as written from ParmVarDecls; it's unclear whether
630249423Sdim    // the standard (C99 6.9.1p10) requires this, but we're following the
631249423Sdim    // precedent set by gcc.
632249423Sdim    QualType Ty;
633249423Sdim    if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
634249423Sdim      Ty = PVD->getOriginalType();
635249423Sdim    else
636249423Sdim      Ty = VD->getType();
637249423Sdim
638193326Sed    if (Ty->isVariablyModifiedType())
639224145Sdim      EmitVariablyModifiedType(Ty);
640193326Sed  }
641226633Sdim  // Emit a location at the end of the prologue.
642226633Sdim  if (CGDebugInfo *DI = getDebugInfo())
643226633Sdim    DI->EmitLocation(Builder, StartLoc);
644193326Sed}
645193326Sed
646263508Sdimvoid CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
647263508Sdim                                       const Stmt *Body) {
648263508Sdim  if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
649249423Sdim    EmitCompoundStmtWithoutScope(*S);
650249423Sdim  else
651263508Sdim    EmitStmt(Body);
652204643Srdivacky}
653204643Srdivacky
654212904Sdim/// Tries to mark the given function nounwind based on the
655212904Sdim/// non-existence of any throwing calls within it.  We believe this is
656212904Sdim/// lightweight enough to do at -O0.
657212904Sdimstatic void TryMarkNoThrow(llvm::Function *F) {
658212904Sdim  // LLVM treats 'nounwind' on a function as part of the type, so we
659212904Sdim  // can't do this on functions that can be overwritten.
660212904Sdim  if (F->mayBeOverridden()) return;
661212904Sdim
662212904Sdim  for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
663212904Sdim    for (llvm::BasicBlock::iterator
664212904Sdim           BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
665226633Sdim      if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) {
666212904Sdim        if (!Call->doesNotThrow())
667212904Sdim          return;
668226633Sdim      } else if (isa<llvm::ResumeInst>(&*BI)) {
669226633Sdim        return;
670226633Sdim      }
671243830Sdim  F->setDoesNotThrow();
672212904Sdim}
673212904Sdim
674263508Sdimstatic void EmitSizedDeallocationFunction(CodeGenFunction &CGF,
675263508Sdim                                          const FunctionDecl *UnsizedDealloc) {
676263508Sdim  // This is a weak discardable definition of the sized deallocation function.
677263508Sdim  CGF.CurFn->setLinkage(llvm::Function::LinkOnceAnyLinkage);
678263508Sdim
679263508Sdim  // Call the unsized deallocation function and forward the first argument
680263508Sdim  // unchanged.
681263508Sdim  llvm::Constant *Unsized = CGF.CGM.GetAddrOfFunction(UnsizedDealloc);
682263508Sdim  CGF.Builder.CreateCall(Unsized, &*CGF.CurFn->arg_begin());
683263508Sdim}
684263508Sdim
685221345Sdimvoid CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
686221345Sdim                                   const CGFunctionInfo &FnInfo) {
687198092Srdivacky  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
688249423Sdim
689193326Sed  // Check if we should generate debug info for this function.
690263508Sdim  if (FD->hasAttr<NoDebugAttr>())
691263508Sdim    DebugInfo = NULL; // disable debug info indefinitely for this function
692198092Srdivacky
693193326Sed  FunctionArgList Args;
694212904Sdim  QualType ResTy = FD->getResultType();
695198092Srdivacky
696200583Srdivacky  CurGD = GD;
697263508Sdim  const CXXMethodDecl *MD;
698263508Sdim  if ((MD = dyn_cast<CXXMethodDecl>(FD)) && MD->isInstance()) {
699263508Sdim    if (CGM.getCXXABI().HasThisReturn(GD))
700263508Sdim      ResTy = MD->getThisType(getContext());
701212904Sdim    CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args);
702263508Sdim  }
703198092Srdivacky
704234353Sdim  for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
705234353Sdim    Args.push_back(FD->getParamDecl(i));
706193326Sed
707204643Srdivacky  SourceRange BodyRange;
708204643Srdivacky  if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
709263508Sdim  CurEHLocation = BodyRange.getEnd();
710199482Srdivacky
711204643Srdivacky  // Emit the standard function prologue.
712221345Sdim  StartFunction(GD, ResTy, Fn, FnInfo, Args, BodyRange.getBegin());
713199482Srdivacky
714204643Srdivacky  // Generate the body of the function.
715204643Srdivacky  if (isa<CXXDestructorDecl>(FD))
716204643Srdivacky    EmitDestructorBody(Args);
717204643Srdivacky  else if (isa<CXXConstructorDecl>(FD))
718204643Srdivacky    EmitConstructorBody(Args);
719243830Sdim  else if (getLangOpts().CUDA &&
720226633Sdim           !CGM.getCodeGenOpts().CUDAIsDevice &&
721226633Sdim           FD->hasAttr<CUDAGlobalAttr>())
722226633Sdim    CGM.getCUDARuntime().EmitDeviceStubBody(*this, Args);
723234353Sdim  else if (isa<CXXConversionDecl>(FD) &&
724234353Sdim           cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
725234353Sdim    // The lambda conversion to block pointer is special; the semantics can't be
726234353Sdim    // expressed in the AST, so IRGen needs to special-case it.
727234353Sdim    EmitLambdaToBlockPointerBody(Args);
728234353Sdim  } else if (isa<CXXMethodDecl>(FD) &&
729234353Sdim             cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
730263508Sdim    // The lambda static invoker function is special, because it forwards or
731234353Sdim    // clones the body of the function call operator (but is actually static).
732234353Sdim    EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
733249423Sdim  } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
734263508Sdim             (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
735263508Sdim              cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
736249423Sdim    // Implicit copy-assignment gets the same special treatment as implicit
737249423Sdim    // copy-constructors.
738249423Sdim    emitImplicitAssignmentOperatorBody(Args);
739263508Sdim  } else if (Stmt *Body = FD->getBody()) {
740263508Sdim    EmitFunctionBody(Args, Body);
741263508Sdim  } else if (FunctionDecl *UnsizedDealloc =
742263508Sdim                 FD->getCorrespondingUnsizedGlobalDeallocationFunction()) {
743263508Sdim    // Global sized deallocation functions get an implicit weak definition if
744263508Sdim    // they don't have an explicit definition.
745263508Sdim    EmitSizedDeallocationFunction(*this, UnsizedDealloc);
746263508Sdim  } else
747263508Sdim    llvm_unreachable("no definition for emitted function");
748203955Srdivacky
749243830Sdim  // C++11 [stmt.return]p2:
750243830Sdim  //   Flowing off the end of a function [...] results in undefined behavior in
751243830Sdim  //   a value-returning function.
752243830Sdim  // C11 6.9.1p12:
753243830Sdim  //   If the '}' that terminates a function is reached, and the value of the
754243830Sdim  //   function call is used by the caller, the behavior is undefined.
755243830Sdim  if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() &&
756243830Sdim      !FD->getResultType()->isVoidType() && Builder.GetInsertBlock()) {
757249423Sdim    if (SanOpts->Return)
758243830Sdim      EmitCheck(Builder.getFalse(), "missing_return",
759243830Sdim                EmitCheckSourceLocation(FD->getLocation()),
760249423Sdim                ArrayRef<llvm::Value *>(), CRK_Unrecoverable);
761243830Sdim    else if (CGM.getCodeGenOpts().OptimizationLevel == 0)
762243830Sdim      Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::trap));
763243830Sdim    Builder.CreateUnreachable();
764243830Sdim    Builder.ClearInsertionPoint();
765243830Sdim  }
766243830Sdim
767204643Srdivacky  // Emit the standard function epilogue.
768204643Srdivacky  FinishFunction(BodyRange.getEnd());
769198092Srdivacky
770212904Sdim  // If we haven't marked the function nothrow through other means, do
771212904Sdim  // a quick pass now to see if we can.
772212904Sdim  if (!CurFn->doesNotThrow())
773212904Sdim    TryMarkNoThrow(CurFn);
774193326Sed}
775193326Sed
776193326Sed/// ContainsLabel - Return true if the statement contains a label in it.  If
777193326Sed/// this statement is not executed normally, it not containing a label means
778193326Sed/// that we can just remove the code.
779193326Sedbool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
780193326Sed  // Null statement, not a label!
781193326Sed  if (S == 0) return false;
782198092Srdivacky
783193326Sed  // If this is a label, we have to emit the code, consider something like:
784193326Sed  // if (0) {  ...  foo:  bar(); }  goto foo;
785221345Sdim  //
786221345Sdim  // TODO: If anyone cared, we could track __label__'s, since we know that you
787221345Sdim  // can't jump to one from outside their declared region.
788193326Sed  if (isa<LabelStmt>(S))
789193326Sed    return true;
790249423Sdim
791193326Sed  // If this is a case/default statement, and we haven't seen a switch, we have
792193326Sed  // to emit the code.
793193326Sed  if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
794193326Sed    return true;
795198092Srdivacky
796193326Sed  // If this is a switch statement, we want to ignore cases below it.
797193326Sed  if (isa<SwitchStmt>(S))
798193326Sed    IgnoreCaseStmts = true;
799198092Srdivacky
800193326Sed  // Scan subexpressions for verboten labels.
801218893Sdim  for (Stmt::const_child_range I = S->children(); I; ++I)
802193326Sed    if (ContainsLabel(*I, IgnoreCaseStmts))
803193326Sed      return true;
804198092Srdivacky
805193326Sed  return false;
806193326Sed}
807193326Sed
808221345Sdim/// containsBreak - Return true if the statement contains a break out of it.
809221345Sdim/// If the statement (recursively) contains a switch or loop with a break
810221345Sdim/// inside of it, this is fine.
811221345Sdimbool CodeGenFunction::containsBreak(const Stmt *S) {
812221345Sdim  // Null statement, not a label!
813221345Sdim  if (S == 0) return false;
814193326Sed
815221345Sdim  // If this is a switch or loop that defines its own break scope, then we can
816221345Sdim  // include it and anything inside of it.
817221345Sdim  if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
818221345Sdim      isa<ForStmt>(S))
819221345Sdim    return false;
820249423Sdim
821221345Sdim  if (isa<BreakStmt>(S))
822221345Sdim    return true;
823249423Sdim
824221345Sdim  // Scan subexpressions for verboten breaks.
825221345Sdim  for (Stmt::const_child_range I = S->children(); I; ++I)
826221345Sdim    if (containsBreak(*I))
827221345Sdim      return true;
828249423Sdim
829221345Sdim  return false;
830221345Sdim}
831221345Sdim
832221345Sdim
833221345Sdim/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
834221345Sdim/// to a constant, or if it does but contains a label, return false.  If it
835221345Sdim/// constant folds return true and set the boolean result in Result.
836221345Sdimbool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
837221345Sdim                                                   bool &ResultBool) {
838239462Sdim  llvm::APSInt ResultInt;
839221345Sdim  if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
840221345Sdim    return false;
841249423Sdim
842221345Sdim  ResultBool = ResultInt.getBoolValue();
843221345Sdim  return true;
844221345Sdim}
845221345Sdim
846221345Sdim/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
847221345Sdim/// to a constant, or if it does but contains a label, return false.  If it
848221345Sdim/// constant folds return true and set the folded value.
849221345Sdimbool CodeGenFunction::
850239462SdimConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &ResultInt) {
851193326Sed  // FIXME: Rename and handle conversion of other evaluatable things
852193326Sed  // to bool.
853234353Sdim  llvm::APSInt Int;
854234353Sdim  if (!Cond->EvaluateAsInt(Int, getContext()))
855221345Sdim    return false;  // Not foldable, not integer or not fully evaluatable.
856234353Sdim
857193326Sed  if (CodeGenFunction::ContainsLabel(Cond))
858221345Sdim    return false;  // Contains a label.
859234353Sdim
860234353Sdim  ResultInt = Int;
861221345Sdim  return true;
862193326Sed}
863193326Sed
864193326Sed
865221345Sdim
866193326Sed/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
867193326Sed/// statement) to the specified blocks.  Based on the condition, this might try
868193326Sed/// to simplify the codegen of the conditional based on the branch.
869193326Sed///
870193326Sedvoid CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
871193326Sed                                           llvm::BasicBlock *TrueBlock,
872193326Sed                                           llvm::BasicBlock *FalseBlock) {
873221345Sdim  Cond = Cond->IgnoreParens();
874198092Srdivacky
875193326Sed  if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
876193326Sed    // Handle X && Y in a condition.
877212904Sdim    if (CondBOp->getOpcode() == BO_LAnd) {
878193326Sed      // If we have "1 && X", simplify the code.  "0 && X" would have constant
879193326Sed      // folded if the case was simple enough.
880221345Sdim      bool ConstantBool = false;
881221345Sdim      if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
882221345Sdim          ConstantBool) {
883193326Sed        // br(1 && X) -> br(X).
884193326Sed        return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
885193326Sed      }
886198092Srdivacky
887193326Sed      // If we have "X && 1", simplify the code to use an uncond branch.
888193326Sed      // "X && 0" would have been constant folded to 0.
889221345Sdim      if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
890221345Sdim          ConstantBool) {
891193326Sed        // br(X && 1) -> br(X).
892193326Sed        return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
893193326Sed      }
894198092Srdivacky
895193326Sed      // Emit the LHS as a conditional.  If the LHS conditional is false, we
896193326Sed      // want to jump to the FalseBlock.
897193326Sed      llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
898218893Sdim
899218893Sdim      ConditionalEvaluation eval(*this);
900193326Sed      EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
901193326Sed      EmitBlock(LHSTrue);
902198092Srdivacky
903203955Srdivacky      // Any temporaries created here are conditional.
904218893Sdim      eval.begin(*this);
905193326Sed      EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
906218893Sdim      eval.end(*this);
907203955Srdivacky
908193326Sed      return;
909221345Sdim    }
910249423Sdim
911221345Sdim    if (CondBOp->getOpcode() == BO_LOr) {
912193326Sed      // If we have "0 || X", simplify the code.  "1 || X" would have constant
913193326Sed      // folded if the case was simple enough.
914221345Sdim      bool ConstantBool = false;
915221345Sdim      if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
916221345Sdim          !ConstantBool) {
917193326Sed        // br(0 || X) -> br(X).
918193326Sed        return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
919193326Sed      }
920198092Srdivacky
921193326Sed      // If we have "X || 0", simplify the code to use an uncond branch.
922193326Sed      // "X || 1" would have been constant folded to 1.
923221345Sdim      if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
924221345Sdim          !ConstantBool) {
925193326Sed        // br(X || 0) -> br(X).
926193326Sed        return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
927193326Sed      }
928198092Srdivacky
929193326Sed      // Emit the LHS as a conditional.  If the LHS conditional is true, we
930193326Sed      // want to jump to the TrueBlock.
931193326Sed      llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
932218893Sdim
933218893Sdim      ConditionalEvaluation eval(*this);
934193326Sed      EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
935193326Sed      EmitBlock(LHSFalse);
936198092Srdivacky
937203955Srdivacky      // Any temporaries created here are conditional.
938218893Sdim      eval.begin(*this);
939193326Sed      EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
940218893Sdim      eval.end(*this);
941203955Srdivacky
942193326Sed      return;
943193326Sed    }
944193326Sed  }
945198092Srdivacky
946193326Sed  if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
947193326Sed    // br(!x, t, f) -> br(x, f, t)
948212904Sdim    if (CondUOp->getOpcode() == UO_LNot)
949193326Sed      return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
950193326Sed  }
951198092Srdivacky
952193326Sed  if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
953234353Sdim    // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
954234353Sdim    llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
955234353Sdim    llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
956193326Sed
957234353Sdim    ConditionalEvaluation cond(*this);
958234353Sdim    EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
959218893Sdim
960234353Sdim    cond.begin(*this);
961234353Sdim    EmitBlock(LHSBlock);
962234353Sdim    EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
963234353Sdim    cond.end(*this);
964218893Sdim
965234353Sdim    cond.begin(*this);
966234353Sdim    EmitBlock(RHSBlock);
967234353Sdim    EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
968234353Sdim    cond.end(*this);
969218893Sdim
970234353Sdim    return;
971193326Sed  }
972193326Sed
973251662Sdim  if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
974251662Sdim    // Conditional operator handling can give us a throw expression as a
975251662Sdim    // condition for a case like:
976251662Sdim    //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
977251662Sdim    // Fold this to:
978251662Sdim    //   br(c, throw x, br(y, t, f))
979251662Sdim    EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
980251662Sdim    return;
981251662Sdim  }
982251662Sdim
983193326Sed  // Emit the code with the fully general case.
984193326Sed  llvm::Value *CondV = EvaluateExprAsBool(Cond);
985193326Sed  Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
986193326Sed}
987193326Sed
988193326Sed/// ErrorUnsupported - Print out an error that codegen doesn't support the
989193326Sed/// specified stmt yet.
990263508Sdimvoid CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
991263508Sdim  CGM.ErrorUnsupported(S, Type);
992193326Sed}
993193326Sed
994218893Sdim/// emitNonZeroVLAInit - Emit the "zero" initialization of a
995218893Sdim/// variable-length array whose elements have a non-zero bit-pattern.
996218893Sdim///
997239462Sdim/// \param baseType the inner-most element type of the array
998218893Sdim/// \param src - a char* pointing to the bit-pattern for a single
999218893Sdim/// base element of the array
1000218893Sdim/// \param sizeInChars - the total size of the VLA, in chars
1001218893Sdimstatic void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
1002249423Sdim                               llvm::Value *dest, llvm::Value *src,
1003218893Sdim                               llvm::Value *sizeInChars) {
1004218893Sdim  std::pair<CharUnits,CharUnits> baseSizeAndAlign
1005218893Sdim    = CGF.getContext().getTypeInfoInChars(baseType);
1006218893Sdim
1007218893Sdim  CGBuilderTy &Builder = CGF.Builder;
1008218893Sdim
1009218893Sdim  llvm::Value *baseSizeInChars
1010218893Sdim    = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
1011218893Sdim
1012226633Sdim  llvm::Type *i8p = Builder.getInt8PtrTy();
1013218893Sdim
1014218893Sdim  llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
1015218893Sdim  llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
1016218893Sdim
1017218893Sdim  llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
1018218893Sdim  llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
1019218893Sdim  llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
1020218893Sdim
1021218893Sdim  // Make a loop over the VLA.  C99 guarantees that the VLA element
1022218893Sdim  // count must be nonzero.
1023218893Sdim  CGF.EmitBlock(loopBB);
1024218893Sdim
1025221345Sdim  llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur");
1026218893Sdim  cur->addIncoming(begin, originBB);
1027218893Sdim
1028218893Sdim  // memcpy the individual element bit-pattern.
1029218893Sdim  Builder.CreateMemCpy(cur, src, baseSizeInChars,
1030218893Sdim                       baseSizeAndAlign.second.getQuantity(),
1031218893Sdim                       /*volatile*/ false);
1032218893Sdim
1033218893Sdim  // Go to the next element.
1034218893Sdim  llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next");
1035218893Sdim
1036218893Sdim  // Leave if that's the end of the VLA.
1037218893Sdim  llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
1038218893Sdim  Builder.CreateCondBr(done, contBB, loopBB);
1039218893Sdim  cur->addIncoming(next, loopBB);
1040218893Sdim
1041218893Sdim  CGF.EmitBlock(contBB);
1042249423Sdim}
1043218893Sdim
1044208600Srdivackyvoid
1045208600SrdivackyCodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
1046207619Srdivacky  // Ignore empty classes in C++.
1047243830Sdim  if (getLangOpts().CPlusPlus) {
1048207619Srdivacky    if (const RecordType *RT = Ty->getAs<RecordType>()) {
1049207619Srdivacky      if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1050207619Srdivacky        return;
1051207619Srdivacky    }
1052207619Srdivacky  }
1053212904Sdim
1054212904Sdim  // Cast the dest ptr to the appropriate i8 pointer type.
1055212904Sdim  unsigned DestAS =
1056212904Sdim    cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
1057226633Sdim  llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
1058193326Sed  if (DestPtr->getType() != BP)
1059226633Sdim    DestPtr = Builder.CreateBitCast(DestPtr, BP);
1060193326Sed
1061193326Sed  // Get size and alignment info for this aggregate.
1062249423Sdim  std::pair<CharUnits, CharUnits> TypeInfo =
1063221345Sdim    getContext().getTypeInfoInChars(Ty);
1064221345Sdim  CharUnits Size = TypeInfo.first;
1065221345Sdim  CharUnits Align = TypeInfo.second;
1066193326Sed
1067218893Sdim  llvm::Value *SizeVal;
1068218893Sdim  const VariableArrayType *vla;
1069218893Sdim
1070193326Sed  // Don't bother emitting a zero-byte memset.
1071221345Sdim  if (Size.isZero()) {
1072218893Sdim    // But note that getTypeInfo returns 0 for a VLA.
1073218893Sdim    if (const VariableArrayType *vlaType =
1074218893Sdim          dyn_cast_or_null<VariableArrayType>(
1075218893Sdim                                          getContext().getAsArrayType(Ty))) {
1076224145Sdim      QualType eltType;
1077224145Sdim      llvm::Value *numElts;
1078224145Sdim      llvm::tie(numElts, eltType) = getVLASize(vlaType);
1079224145Sdim
1080224145Sdim      SizeVal = numElts;
1081224145Sdim      CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
1082224145Sdim      if (!eltSize.isOne())
1083224145Sdim        SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
1084218893Sdim      vla = vlaType;
1085218893Sdim    } else {
1086218893Sdim      return;
1087218893Sdim    }
1088218893Sdim  } else {
1089224145Sdim    SizeVal = CGM.getSize(Size);
1090218893Sdim    vla = 0;
1091218893Sdim  }
1092198092Srdivacky
1093212904Sdim  // If the type contains a pointer to data member we can't memset it to zero.
1094212904Sdim  // Instead, create a null constant and copy it to the destination.
1095218893Sdim  // TODO: there are other patterns besides zero that we can usefully memset,
1096218893Sdim  // like -1, which happens to be the pattern used by member-pointers.
1097212904Sdim  if (!CGM.getTypes().isZeroInitializable(Ty)) {
1098218893Sdim    // For a VLA, emit a single element, then splat that over the VLA.
1099218893Sdim    if (vla) Ty = getContext().getBaseElementType(vla);
1100218893Sdim
1101212904Sdim    llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1102212904Sdim
1103249423Sdim    llvm::GlobalVariable *NullVariable =
1104212904Sdim      new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1105249423Sdim                               /*isConstant=*/true,
1106212904Sdim                               llvm::GlobalVariable::PrivateLinkage,
1107226633Sdim                               NullConstant, Twine());
1108212904Sdim    llvm::Value *SrcPtr =
1109212904Sdim      Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
1110212904Sdim
1111218893Sdim    if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
1112212904Sdim
1113212904Sdim    // Get and call the appropriate llvm.memcpy overload.
1114221345Sdim    Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false);
1115212904Sdim    return;
1116249423Sdim  }
1117249423Sdim
1118212904Sdim  // Otherwise, just memset the whole thing to zero.  This is legal
1119212904Sdim  // because in LLVM, all default initializers (other than the ones we just
1120212904Sdim  // handled above) are guaranteed to have a bit pattern of all zeros.
1121249423Sdim  Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal,
1122221345Sdim                       Align.getQuantity(), false);
1123193326Sed}
1124193326Sed
1125218893Sdimllvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
1126198893Srdivacky  // Make sure that there is a block for the indirect goto.
1127198893Srdivacky  if (IndirectBranch == 0)
1128198893Srdivacky    GetIndirectGotoBlock();
1129249423Sdim
1130212904Sdim  llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
1131249423Sdim
1132198893Srdivacky  // Make sure the indirect branch includes all of the address-taken blocks.
1133198893Srdivacky  IndirectBranch->addDestination(BB);
1134198893Srdivacky  return llvm::BlockAddress::get(CurFn, BB);
1135198092Srdivacky}
1136198092Srdivacky
1137198092Srdivackyllvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
1138198893Srdivacky  // If we already made the indirect branch for indirect goto, return its block.
1139198893Srdivacky  if (IndirectBranch) return IndirectBranch->getParent();
1140249423Sdim
1141198893Srdivacky  CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
1142249423Sdim
1143198092Srdivacky  // Create the PHI node that indirect gotos will add entries to.
1144221345Sdim  llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
1145221345Sdim                                              "indirect.goto.dest");
1146249423Sdim
1147198893Srdivacky  // Create the indirect branch instruction.
1148198893Srdivacky  IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1149198893Srdivacky  return IndirectBranch->getParent();
1150193326Sed}
1151193326Sed
1152224145Sdim/// Computes the length of an array in elements, as well as the base
1153224145Sdim/// element type and a properly-typed first element pointer.
1154224145Sdimllvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
1155224145Sdim                                              QualType &baseType,
1156224145Sdim                                              llvm::Value *&addr) {
1157224145Sdim  const ArrayType *arrayType = origArrayType;
1158198092Srdivacky
1159224145Sdim  // If it's a VLA, we have to load the stored size.  Note that
1160224145Sdim  // this is the size of the VLA in bytes, not its size in elements.
1161224145Sdim  llvm::Value *numVLAElements = 0;
1162224145Sdim  if (isa<VariableArrayType>(arrayType)) {
1163224145Sdim    numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
1164224145Sdim
1165224145Sdim    // Walk into all VLAs.  This doesn't require changes to addr,
1166224145Sdim    // which has type T* where T is the first non-VLA element type.
1167224145Sdim    do {
1168224145Sdim      QualType elementType = arrayType->getElementType();
1169224145Sdim      arrayType = getContext().getAsArrayType(elementType);
1170224145Sdim
1171224145Sdim      // If we only have VLA components, 'addr' requires no adjustment.
1172224145Sdim      if (!arrayType) {
1173224145Sdim        baseType = elementType;
1174224145Sdim        return numVLAElements;
1175224145Sdim      }
1176224145Sdim    } while (isa<VariableArrayType>(arrayType));
1177224145Sdim
1178224145Sdim    // We get out here only if we find a constant array type
1179224145Sdim    // inside the VLA.
1180224145Sdim  }
1181224145Sdim
1182224145Sdim  // We have some number of constant-length arrays, so addr should
1183224145Sdim  // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
1184224145Sdim  // down to the first element of addr.
1185226633Sdim  SmallVector<llvm::Value*, 8> gepIndices;
1186224145Sdim
1187224145Sdim  // GEP down to the array type.
1188224145Sdim  llvm::ConstantInt *zero = Builder.getInt32(0);
1189224145Sdim  gepIndices.push_back(zero);
1190224145Sdim
1191224145Sdim  uint64_t countFromCLAs = 1;
1192239462Sdim  QualType eltType;
1193224145Sdim
1194226633Sdim  llvm::ArrayType *llvmArrayType =
1195239462Sdim    dyn_cast<llvm::ArrayType>(
1196224145Sdim      cast<llvm::PointerType>(addr->getType())->getElementType());
1197239462Sdim  while (llvmArrayType) {
1198224145Sdim    assert(isa<ConstantArrayType>(arrayType));
1199224145Sdim    assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
1200224145Sdim             == llvmArrayType->getNumElements());
1201224145Sdim
1202224145Sdim    gepIndices.push_back(zero);
1203224145Sdim    countFromCLAs *= llvmArrayType->getNumElements();
1204239462Sdim    eltType = arrayType->getElementType();
1205224145Sdim
1206224145Sdim    llvmArrayType =
1207224145Sdim      dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
1208224145Sdim    arrayType = getContext().getAsArrayType(arrayType->getElementType());
1209239462Sdim    assert((!llvmArrayType || arrayType) &&
1210239462Sdim           "LLVM and Clang types are out-of-synch");
1211224145Sdim  }
1212224145Sdim
1213239462Sdim  if (arrayType) {
1214239462Sdim    // From this point onwards, the Clang array type has been emitted
1215239462Sdim    // as some other type (probably a packed struct). Compute the array
1216239462Sdim    // size, and just emit the 'begin' expression as a bitcast.
1217239462Sdim    while (arrayType) {
1218239462Sdim      countFromCLAs *=
1219239462Sdim          cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
1220239462Sdim      eltType = arrayType->getElementType();
1221239462Sdim      arrayType = getContext().getAsArrayType(eltType);
1222239462Sdim    }
1223224145Sdim
1224243830Sdim    unsigned AddressSpace = addr->getType()->getPointerAddressSpace();
1225239462Sdim    llvm::Type *BaseType = ConvertType(eltType)->getPointerTo(AddressSpace);
1226239462Sdim    addr = Builder.CreateBitCast(addr, BaseType, "array.begin");
1227239462Sdim  } else {
1228239462Sdim    // Create the actual GEP.
1229239462Sdim    addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin");
1230239462Sdim  }
1231224145Sdim
1232239462Sdim  baseType = eltType;
1233239462Sdim
1234224145Sdim  llvm::Value *numElements
1235224145Sdim    = llvm::ConstantInt::get(SizeTy, countFromCLAs);
1236224145Sdim
1237224145Sdim  // If we had any VLA dimensions, factor them in.
1238224145Sdim  if (numVLAElements)
1239224145Sdim    numElements = Builder.CreateNUWMul(numVLAElements, numElements);
1240224145Sdim
1241224145Sdim  return numElements;
1242193326Sed}
1243193326Sed
1244224145Sdimstd::pair<llvm::Value*, QualType>
1245224145SdimCodeGenFunction::getVLASize(QualType type) {
1246224145Sdim  const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
1247224145Sdim  assert(vla && "type was not a variable array type!");
1248224145Sdim  return getVLASize(vla);
1249224145Sdim}
1250224145Sdim
1251224145Sdimstd::pair<llvm::Value*, QualType>
1252224145SdimCodeGenFunction::getVLASize(const VariableArrayType *type) {
1253224145Sdim  // The number of elements so far; always size_t.
1254224145Sdim  llvm::Value *numElements = 0;
1255224145Sdim
1256224145Sdim  QualType elementType;
1257224145Sdim  do {
1258224145Sdim    elementType = type->getElementType();
1259224145Sdim    llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
1260224145Sdim    assert(vlaSize && "no size for VLA!");
1261224145Sdim    assert(vlaSize->getType() == SizeTy);
1262224145Sdim
1263224145Sdim    if (!numElements) {
1264224145Sdim      numElements = vlaSize;
1265224145Sdim    } else {
1266224145Sdim      // It's undefined behavior if this wraps around, so mark it that way.
1267243830Sdim      // FIXME: Teach -fcatch-undefined-behavior to trap this.
1268224145Sdim      numElements = Builder.CreateNUWMul(numElements, vlaSize);
1269224145Sdim    }
1270224145Sdim  } while ((type = getContext().getAsVariableArrayType(elementType)));
1271224145Sdim
1272224145Sdim  return std::pair<llvm::Value*,QualType>(numElements, elementType);
1273224145Sdim}
1274224145Sdim
1275224145Sdimvoid CodeGenFunction::EmitVariablyModifiedType(QualType type) {
1276224145Sdim  assert(type->isVariablyModifiedType() &&
1277193326Sed         "Must pass variably modified type to EmitVLASizes!");
1278198092Srdivacky
1279198092Srdivacky  EnsureInsertPoint();
1280198092Srdivacky
1281224145Sdim  // We're going to walk down into the type and look for VLA
1282224145Sdim  // expressions.
1283224145Sdim  do {
1284224145Sdim    assert(type->isVariablyModifiedType());
1285198092Srdivacky
1286224145Sdim    const Type *ty = type.getTypePtr();
1287224145Sdim    switch (ty->getTypeClass()) {
1288234353Sdim
1289224145Sdim#define TYPE(Class, Base)
1290224145Sdim#define ABSTRACT_TYPE(Class, Base)
1291234353Sdim#define NON_CANONICAL_TYPE(Class, Base)
1292224145Sdim#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1293234353Sdim#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
1294224145Sdim#include "clang/AST/TypeNodes.def"
1295234353Sdim      llvm_unreachable("unexpected dependent type!");
1296198092Srdivacky
1297224145Sdim    // These types are never variably-modified.
1298224145Sdim    case Type::Builtin:
1299224145Sdim    case Type::Complex:
1300224145Sdim    case Type::Vector:
1301224145Sdim    case Type::ExtVector:
1302224145Sdim    case Type::Record:
1303224145Sdim    case Type::Enum:
1304234353Sdim    case Type::Elaborated:
1305234353Sdim    case Type::TemplateSpecialization:
1306224145Sdim    case Type::ObjCObject:
1307224145Sdim    case Type::ObjCInterface:
1308224145Sdim    case Type::ObjCObjectPointer:
1309224145Sdim      llvm_unreachable("type class is never variably-modified!");
1310198092Srdivacky
1311263508Sdim    case Type::Decayed:
1312263508Sdim      type = cast<DecayedType>(ty)->getPointeeType();
1313263508Sdim      break;
1314263508Sdim
1315224145Sdim    case Type::Pointer:
1316224145Sdim      type = cast<PointerType>(ty)->getPointeeType();
1317224145Sdim      break;
1318198092Srdivacky
1319224145Sdim    case Type::BlockPointer:
1320224145Sdim      type = cast<BlockPointerType>(ty)->getPointeeType();
1321224145Sdim      break;
1322198092Srdivacky
1323224145Sdim    case Type::LValueReference:
1324224145Sdim    case Type::RValueReference:
1325224145Sdim      type = cast<ReferenceType>(ty)->getPointeeType();
1326224145Sdim      break;
1327198092Srdivacky
1328224145Sdim    case Type::MemberPointer:
1329224145Sdim      type = cast<MemberPointerType>(ty)->getPointeeType();
1330224145Sdim      break;
1331198092Srdivacky
1332224145Sdim    case Type::ConstantArray:
1333224145Sdim    case Type::IncompleteArray:
1334224145Sdim      // Losing element qualification here is fine.
1335224145Sdim      type = cast<ArrayType>(ty)->getElementType();
1336224145Sdim      break;
1337218893Sdim
1338224145Sdim    case Type::VariableArray: {
1339224145Sdim      // Losing element qualification here is fine.
1340224145Sdim      const VariableArrayType *vat = cast<VariableArrayType>(ty);
1341224145Sdim
1342224145Sdim      // Unknown size indication requires no size computation.
1343224145Sdim      // Otherwise, evaluate and record it.
1344224145Sdim      if (const Expr *size = vat->getSizeExpr()) {
1345224145Sdim        // It's possible that we might have emitted this already,
1346224145Sdim        // e.g. with a typedef and a pointer to it.
1347224145Sdim        llvm::Value *&entry = VLASizeMap[size];
1348224145Sdim        if (!entry) {
1349243830Sdim          llvm::Value *Size = EmitScalarExpr(size);
1350243830Sdim
1351243830Sdim          // C11 6.7.6.2p5:
1352243830Sdim          //   If the size is an expression that is not an integer constant
1353243830Sdim          //   expression [...] each time it is evaluated it shall have a value
1354243830Sdim          //   greater than zero.
1355249423Sdim          if (SanOpts->VLABound &&
1356243830Sdim              size->getType()->isSignedIntegerType()) {
1357243830Sdim            llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
1358243830Sdim            llvm::Constant *StaticArgs[] = {
1359243830Sdim              EmitCheckSourceLocation(size->getLocStart()),
1360243830Sdim              EmitCheckTypeDescriptor(size->getType())
1361243830Sdim            };
1362243830Sdim            EmitCheck(Builder.CreateICmpSGT(Size, Zero),
1363249423Sdim                      "vla_bound_not_positive", StaticArgs, Size,
1364249423Sdim                      CRK_Recoverable);
1365243830Sdim          }
1366243830Sdim
1367224145Sdim          // Always zexting here would be wrong if it weren't
1368224145Sdim          // undefined behavior to have a negative bound.
1369243830Sdim          entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
1370224145Sdim        }
1371224145Sdim      }
1372224145Sdim      type = vat->getElementType();
1373224145Sdim      break;
1374224145Sdim    }
1375224145Sdim
1376234353Sdim    case Type::FunctionProto:
1377224145Sdim    case Type::FunctionNoProto:
1378224145Sdim      type = cast<FunctionType>(ty)->getResultType();
1379224145Sdim      break;
1380226633Sdim
1381234353Sdim    case Type::Paren:
1382234353Sdim    case Type::TypeOf:
1383234353Sdim    case Type::UnaryTransform:
1384234353Sdim    case Type::Attributed:
1385234353Sdim    case Type::SubstTemplateTypeParm:
1386263508Sdim    case Type::PackExpansion:
1387234353Sdim      // Keep walking after single level desugaring.
1388234353Sdim      type = type.getSingleStepDesugaredType(getContext());
1389234353Sdim      break;
1390234353Sdim
1391234353Sdim    case Type::Typedef:
1392234353Sdim    case Type::Decltype:
1393234353Sdim    case Type::Auto:
1394234353Sdim      // Stop walking: nothing to do.
1395234353Sdim      return;
1396234353Sdim
1397234353Sdim    case Type::TypeOfExpr:
1398234353Sdim      // Stop walking: emit typeof expression.
1399234353Sdim      EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
1400234353Sdim      return;
1401234353Sdim
1402226633Sdim    case Type::Atomic:
1403226633Sdim      type = cast<AtomicType>(ty)->getValueType();
1404226633Sdim      break;
1405224145Sdim    }
1406224145Sdim  } while (type->isVariablyModifiedType());
1407193326Sed}
1408193326Sed
1409193326Sedllvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
1410218893Sdim  if (getContext().getBuiltinVaListType()->isArrayType())
1411193326Sed    return EmitScalarExpr(E);
1412193326Sed  return EmitLValue(E).getAddress();
1413193326Sed}
1414193326Sed
1415249423Sdimvoid CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
1416218893Sdim                                              llvm::Constant *Init) {
1417218893Sdim  assert (Init && "Invalid DeclRefExpr initializer!");
1418218893Sdim  if (CGDebugInfo *Dbg = getDebugInfo())
1419243830Sdim    if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
1420239462Sdim      Dbg->EmitGlobalVariable(E->getDecl(), Init);
1421212904Sdim}
1422210299Sed
1423218893SdimCodeGenFunction::PeepholeProtection
1424218893SdimCodeGenFunction::protectFromPeepholes(RValue rvalue) {
1425218893Sdim  // At the moment, the only aggressive peephole we do in IR gen
1426218893Sdim  // is trunc(zext) folding, but if we add more, we can easily
1427218893Sdim  // extend this protection.
1428193326Sed
1429218893Sdim  if (!rvalue.isScalar()) return PeepholeProtection();
1430218893Sdim  llvm::Value *value = rvalue.getScalarVal();
1431218893Sdim  if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
1432198092Srdivacky
1433218893Sdim  // Just make an extra bitcast.
1434218893Sdim  assert(HaveInsertPoint());
1435218893Sdim  llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
1436218893Sdim                                                  Builder.GetInsertBlock());
1437198092Srdivacky
1438218893Sdim  PeepholeProtection protection;
1439218893Sdim  protection.Inst = inst;
1440218893Sdim  return protection;
1441210299Sed}
1442198092Srdivacky
1443218893Sdimvoid CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
1444218893Sdim  if (!protection.Inst) return;
1445198092Srdivacky
1446218893Sdim  // In theory, we could try to duplicate the peepholes now, but whatever.
1447218893Sdim  protection.Inst->eraseFromParent();
1448210299Sed}
1449226633Sdim
1450226633Sdimllvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
1451226633Sdim                                                 llvm::Value *AnnotatedVal,
1452249423Sdim                                                 StringRef AnnotationStr,
1453226633Sdim                                                 SourceLocation Location) {
1454226633Sdim  llvm::Value *Args[4] = {
1455226633Sdim    AnnotatedVal,
1456226633Sdim    Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
1457226633Sdim    Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
1458226633Sdim    CGM.EmitAnnotationLineNo(Location)
1459226633Sdim  };
1460226633Sdim  return Builder.CreateCall(AnnotationFn, Args);
1461226633Sdim}
1462226633Sdim
1463226633Sdimvoid CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
1464226633Sdim  assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1465226633Sdim  // FIXME We create a new bitcast for every annotation because that's what
1466226633Sdim  // llvm-gcc was doing.
1467226633Sdim  for (specific_attr_iterator<AnnotateAttr>
1468226633Sdim       ai = D->specific_attr_begin<AnnotateAttr>(),
1469226633Sdim       ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
1470226633Sdim    EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
1471226633Sdim                       Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
1472226633Sdim                       (*ai)->getAnnotation(), D->getLocation());
1473226633Sdim}
1474226633Sdim
1475226633Sdimllvm::Value *CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
1476226633Sdim                                                   llvm::Value *V) {
1477226633Sdim  assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1478226633Sdim  llvm::Type *VTy = V->getType();
1479226633Sdim  llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
1480226633Sdim                                    CGM.Int8PtrTy);
1481226633Sdim
1482226633Sdim  for (specific_attr_iterator<AnnotateAttr>
1483226633Sdim       ai = D->specific_attr_begin<AnnotateAttr>(),
1484226633Sdim       ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) {
1485226633Sdim    // FIXME Always emit the cast inst so we can differentiate between
1486226633Sdim    // annotation on the first field of a struct and annotation on the struct
1487226633Sdim    // itself.
1488226633Sdim    if (VTy != CGM.Int8PtrTy)
1489226633Sdim      V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
1490226633Sdim    V = EmitAnnotationCall(F, V, (*ai)->getAnnotation(), D->getLocation());
1491226633Sdim    V = Builder.CreateBitCast(V, VTy);
1492226633Sdim  }
1493226633Sdim
1494226633Sdim  return V;
1495226633Sdim}
1496263508Sdim
1497263508SdimCodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
1498