clang  3.7.0
CodeGenFunction.cpp
Go to the documentation of this file.
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 "CGCleanup.h"
16 #include "CGCUDARuntime.h"
17 #include "CGCXXABI.h"
18 #include "CGDebugInfo.h"
19 #include "CGOpenMPRuntime.h"
20 #include "CodeGenModule.h"
21 #include "CodeGenPGO.h"
22 #include "TargetInfo.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/Decl.h"
25 #include "clang/AST/DeclCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/TargetInfo.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/MDBuilder.h"
33 #include "llvm/IR/Operator.h"
34 using namespace clang;
35 using namespace CodeGen;
36 
37 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
38  : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
39  Builder(cgm.getModule().getContext(), llvm::ConstantFolder(),
40  CGBuilderInserterTy(this)),
41  CurFn(nullptr), CapturedStmtInfo(nullptr),
42  SanOpts(CGM.getLangOpts().Sanitize), IsSanitizerScope(false),
43  CurFuncIsThunk(false), AutoreleaseResult(false), SawAsmBlock(false),
44  IsOutlinedSEHHelper(false), BlockInfo(nullptr), BlockPointer(nullptr),
45  LambdaThisCaptureField(nullptr), NormalCleanupDest(nullptr),
46  NextCleanupDestIndex(1), FirstBlockInfo(nullptr), EHResumeBlock(nullptr),
47  ExceptionSlot(nullptr), EHSelectorSlot(nullptr),
48  DebugInfo(CGM.getModuleDebugInfo()),
49  DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(nullptr),
50  PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr),
51  CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0),
52  NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr),
53  CXXABIThisValue(nullptr), CXXThisValue(nullptr),
54  CXXDefaultInitExprThis(nullptr), CXXStructorImplicitParamDecl(nullptr),
55  CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
56  CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
57  TerminateHandler(nullptr), TrapBB(nullptr) {
58  if (!suppressNewContext)
60 
61  llvm::FastMathFlags FMF;
62  if (CGM.getLangOpts().FastMath)
63  FMF.setUnsafeAlgebra();
64  if (CGM.getLangOpts().FiniteMathOnly) {
65  FMF.setNoNaNs();
66  FMF.setNoInfs();
67  }
68  if (CGM.getCodeGenOpts().NoNaNsFPMath) {
69  FMF.setNoNaNs();
70  }
71  if (CGM.getCodeGenOpts().NoSignedZeros) {
72  FMF.setNoSignedZeros();
73  }
74  if (CGM.getCodeGenOpts().ReciprocalMath) {
75  FMF.setAllowReciprocal();
76  }
77  Builder.SetFastMathFlags(FMF);
78 }
79 
81  assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
82 
83  // If there are any unclaimed block infos, go ahead and destroy them
84  // now. This can happen if IR-gen gets clever and skips evaluating
85  // something.
86  if (FirstBlockInfo)
88 
89  if (getLangOpts().OpenMP) {
90  CGM.getOpenMPRuntime().functionFinished(*this);
91  }
92 }
93 
95  CharUnits Alignment;
97  Alignment = getContext().getTypeAlignInChars(T);
98  unsigned MaxAlign = getContext().getLangOpts().MaxTypeAlign;
99  if (MaxAlign && Alignment.getQuantity() > MaxAlign &&
101  Alignment = CharUnits::fromQuantity(MaxAlign);
102  }
103  return LValue::MakeAddr(V, T, Alignment, getContext(), CGM.getTBAAInfo(T));
104 }
105 
107  return CGM.getTypes().ConvertTypeForMem(T);
108 }
109 
111  return CGM.getTypes().ConvertType(T);
112 }
113 
115  type = type.getCanonicalType();
116  while (true) {
117  switch (type->getTypeClass()) {
118 #define TYPE(name, parent)
119 #define ABSTRACT_TYPE(name, parent)
120 #define NON_CANONICAL_TYPE(name, parent) case Type::name:
121 #define DEPENDENT_TYPE(name, parent) case Type::name:
122 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
123 #include "clang/AST/TypeNodes.def"
124  llvm_unreachable("non-canonical or dependent type in IR-generation");
125 
126  case Type::Auto:
127  llvm_unreachable("undeduced auto type in IR-generation");
128 
129  // Various scalar types.
130  case Type::Builtin:
131  case Type::Pointer:
132  case Type::BlockPointer:
133  case Type::LValueReference:
134  case Type::RValueReference:
135  case Type::MemberPointer:
136  case Type::Vector:
137  case Type::ExtVector:
138  case Type::FunctionProto:
139  case Type::FunctionNoProto:
140  case Type::Enum:
141  case Type::ObjCObjectPointer:
142  return TEK_Scalar;
143 
144  // Complexes.
145  case Type::Complex:
146  return TEK_Complex;
147 
148  // Arrays, records, and Objective-C objects.
149  case Type::ConstantArray:
150  case Type::IncompleteArray:
151  case Type::VariableArray:
152  case Type::Record:
153  case Type::ObjCObject:
154  case Type::ObjCInterface:
155  return TEK_Aggregate;
156 
157  // We operate on atomic values according to their underlying type.
158  case Type::Atomic:
159  type = cast<AtomicType>(type)->getValueType();
160  continue;
161  }
162  llvm_unreachable("unknown type kind!");
163  }
164 }
165 
167  // For cleanliness, we try to avoid emitting the return block for
168  // simple cases.
169  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
170 
171  if (CurBB) {
172  assert(!CurBB->getTerminator() && "Unexpected terminated block.");
173 
174  // We have a valid insert point, reuse it if it is empty or there are no
175  // explicit jumps to the return block.
176  if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
177  ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
178  delete ReturnBlock.getBlock();
179  } else
181  return llvm::DebugLoc();
182  }
183 
184  // Otherwise, if the return block is the target of a single direct
185  // branch then we can just put the code in that block instead. This
186  // cleans up functions which started with a unified return block.
187  if (ReturnBlock.getBlock()->hasOneUse()) {
188  llvm::BranchInst *BI =
189  dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
190  if (BI && BI->isUnconditional() &&
191  BI->getSuccessor(0) == ReturnBlock.getBlock()) {
192  // Record/return the DebugLoc of the simple 'return' expression to be used
193  // later by the actual 'ret' instruction.
194  llvm::DebugLoc Loc = BI->getDebugLoc();
195  Builder.SetInsertPoint(BI->getParent());
196  BI->eraseFromParent();
197  delete ReturnBlock.getBlock();
198  return Loc;
199  }
200  }
201 
202  // FIXME: We are at an unreachable point, there is no reason to emit the block
203  // unless it has uses. However, we still need a place to put the debug
204  // region.end for now.
205 
207  return llvm::DebugLoc();
208 }
209 
210 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
211  if (!BB) return;
212  if (!BB->use_empty())
213  return CGF.CurFn->getBasicBlockList().push_back(BB);
214  delete BB;
215 }
216 
218  assert(BreakContinueStack.empty() &&
219  "mismatched push/pop in break/continue stack!");
220 
221  bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
222  && NumSimpleReturnExprs == NumReturnExprs
223  && ReturnBlock.getBlock()->use_empty();
224  // Usually the return expression is evaluated before the cleanup
225  // code. If the function contains only a simple return statement,
226  // such as a constant, the location before the cleanup code becomes
227  // the last useful breakpoint in the function, because the simple
228  // return expression will be evaluated after the cleanup code. To be
229  // safe, set the debug location for cleanup code to the location of
230  // the return statement. Otherwise the cleanup code should be at the
231  // end of the function's lexical scope.
232  //
233  // If there are multiple branches to the return block, the branch
234  // instructions will get the location of the return statements and
235  // all will be fine.
236  if (CGDebugInfo *DI = getDebugInfo()) {
237  if (OnlySimpleReturnStmts)
238  DI->EmitLocation(Builder, LastStopPoint);
239  else
240  DI->EmitLocation(Builder, EndLoc);
241  }
242 
243  // Pop any cleanups that might have been associated with the
244  // parameters. Do this in whatever block we're currently in; it's
245  // important to do this before we enter the return block or return
246  // edges will be *really* confused.
247  bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
248  bool HasOnlyLifetimeMarkers =
250  bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
251  if (HasCleanups) {
252  // Make sure the line table doesn't jump back into the body for
253  // the ret after it's been at EndLoc.
254  if (CGDebugInfo *DI = getDebugInfo())
255  if (OnlySimpleReturnStmts)
256  DI->EmitLocation(Builder, EndLoc);
257 
259  }
260 
261  // Emit function epilog (to return).
262  llvm::DebugLoc Loc = EmitReturnBlock();
263 
265  EmitFunctionInstrumentation("__cyg_profile_func_exit");
266 
267  // Emit debug descriptor for function end.
268  if (CGDebugInfo *DI = getDebugInfo())
269  DI->EmitFunctionEnd(Builder);
270 
271  // Reset the debug location to that of the simple 'return' expression, if any
272  // rather than that of the end of the function's scope '}'.
273  ApplyDebugLocation AL(*this, Loc);
274  EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
276 
277  assert(EHStack.empty() &&
278  "did not remove all scopes from cleanup stack!");
279 
280  // If someone did an indirect goto, emit the indirect goto block at the end of
281  // the function.
282  if (IndirectBranch) {
283  EmitBlock(IndirectBranch->getParent());
284  Builder.ClearInsertionPoint();
285  }
286 
287  // If some of our locals escaped, insert a call to llvm.localescape in the
288  // entry block.
289  if (!EscapedLocals.empty()) {
290  // Invert the map from local to index into a simple vector. There should be
291  // no holes.
293  EscapeArgs.resize(EscapedLocals.size());
294  for (auto &Pair : EscapedLocals)
295  EscapeArgs[Pair.second] = Pair.first;
296  llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
297  &CGM.getModule(), llvm::Intrinsic::localescape);
298  CGBuilderTy(AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
299  }
300 
301  // Remove the AllocaInsertPt instruction, which is just a convenience for us.
302  llvm::Instruction *Ptr = AllocaInsertPt;
303  AllocaInsertPt = nullptr;
304  Ptr->eraseFromParent();
305 
306  // If someone took the address of a label but never did an indirect goto, we
307  // made a zero entry PHI node, which is illegal, zap it now.
308  if (IndirectBranch) {
309  llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
310  if (PN->getNumIncomingValues() == 0) {
311  PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
312  PN->eraseFromParent();
313  }
314  }
315 
316  EmitIfUsed(*this, EHResumeBlock);
317  EmitIfUsed(*this, TerminateLandingPad);
318  EmitIfUsed(*this, TerminateHandler);
319  EmitIfUsed(*this, UnreachableBlock);
320 
321  if (CGM.getCodeGenOpts().EmitDeclMetadata)
322  EmitDeclMetadata();
323 
324  for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
325  I = DeferredReplacements.begin(),
326  E = DeferredReplacements.end();
327  I != E; ++I) {
328  I->first->replaceAllUsesWith(I->second);
329  I->first->eraseFromParent();
330  }
331 }
332 
333 /// ShouldInstrumentFunction - Return true if the current function should be
334 /// instrumented with __cyg_profile_func_* calls
336  if (!CGM.getCodeGenOpts().InstrumentFunctions)
337  return false;
338  if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
339  return false;
340  return true;
341 }
342 
343 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
344 /// instrumentation function with the current function and the call site, if
345 /// function instrumentation is enabled.
347  // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
348  llvm::PointerType *PointerTy = Int8PtrTy;
349  llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
350  llvm::FunctionType *FunctionTy =
351  llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
352 
353  llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
354  llvm::CallInst *CallSite = Builder.CreateCall(
355  CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
356  llvm::ConstantInt::get(Int32Ty, 0),
357  "callsite");
358 
359  llvm::Value *args[] = {
360  llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
361  CallSite
362  };
363 
364  EmitNounwindRuntimeCall(F, args);
365 }
366 
368  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
369 
370  llvm::Constant *MCountFn =
371  CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName());
372  EmitNounwindRuntimeCall(MCountFn);
373 }
374 
375 // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
376 // information in the program executable. The argument information stored
377 // includes the argument name, its type, the address and access qualifiers used.
378 static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
379  CodeGenModule &CGM, llvm::LLVMContext &Context,
380  SmallVector<llvm::Metadata *, 5> &kernelMDArgs,
381  CGBuilderTy &Builder, ASTContext &ASTCtx) {
382  // Create MDNodes that represent the kernel arg metadata.
383  // Each MDNode is a list in the form of "key", N number of values which is
384  // the same number of values as their are kernel arguments.
385 
386  const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
387 
388  // MDNode for the kernel argument address space qualifiers.
390  addressQuals.push_back(llvm::MDString::get(Context, "kernel_arg_addr_space"));
391 
392  // MDNode for the kernel argument access qualifiers (images only).
394  accessQuals.push_back(llvm::MDString::get(Context, "kernel_arg_access_qual"));
395 
396  // MDNode for the kernel argument type names.
398  argTypeNames.push_back(llvm::MDString::get(Context, "kernel_arg_type"));
399 
400  // MDNode for the kernel argument base type names.
401  SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
402  argBaseTypeNames.push_back(
403  llvm::MDString::get(Context, "kernel_arg_base_type"));
404 
405  // MDNode for the kernel argument type qualifiers.
407  argTypeQuals.push_back(llvm::MDString::get(Context, "kernel_arg_type_qual"));
408 
409  // MDNode for the kernel argument names.
411  argNames.push_back(llvm::MDString::get(Context, "kernel_arg_name"));
412 
413  for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
414  const ParmVarDecl *parm = FD->getParamDecl(i);
415  QualType ty = parm->getType();
416  std::string typeQuals;
417 
418  if (ty->isPointerType()) {
419  QualType pointeeTy = ty->getPointeeType();
420 
421  // Get address qualifier.
422  addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
423  ASTCtx.getTargetAddressSpace(pointeeTy.getAddressSpace()))));
424 
425  // Get argument type name.
426  std::string typeName =
427  pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
428 
429  // Turn "unsigned type" to "utype"
430  std::string::size_type pos = typeName.find("unsigned");
431  if (pointeeTy.isCanonical() && pos != std::string::npos)
432  typeName.erase(pos+1, 8);
433 
434  argTypeNames.push_back(llvm::MDString::get(Context, typeName));
435 
436  std::string baseTypeName =
438  Policy) +
439  "*";
440 
441  // Turn "unsigned type" to "utype"
442  pos = baseTypeName.find("unsigned");
443  if (pos != std::string::npos)
444  baseTypeName.erase(pos+1, 8);
445 
446  argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
447 
448  // Get argument type qualifiers:
449  if (ty.isRestrictQualified())
450  typeQuals = "restrict";
451  if (pointeeTy.isConstQualified() ||
452  (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
453  typeQuals += typeQuals.empty() ? "const" : " const";
454  if (pointeeTy.isVolatileQualified())
455  typeQuals += typeQuals.empty() ? "volatile" : " volatile";
456  } else {
457  uint32_t AddrSpc = 0;
458  if (ty->isImageType())
459  AddrSpc =
461 
462  addressQuals.push_back(
463  llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
464 
465  // Get argument type name.
466  std::string typeName = ty.getUnqualifiedType().getAsString(Policy);
467 
468  // Turn "unsigned type" to "utype"
469  std::string::size_type pos = typeName.find("unsigned");
470  if (ty.isCanonical() && pos != std::string::npos)
471  typeName.erase(pos+1, 8);
472 
473  argTypeNames.push_back(llvm::MDString::get(Context, typeName));
474 
475  std::string baseTypeName =
477 
478  // Turn "unsigned type" to "utype"
479  pos = baseTypeName.find("unsigned");
480  if (pos != std::string::npos)
481  baseTypeName.erase(pos+1, 8);
482 
483  argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
484 
485  // Get argument type qualifiers:
486  if (ty.isConstQualified())
487  typeQuals = "const";
488  if (ty.isVolatileQualified())
489  typeQuals += typeQuals.empty() ? "volatile" : " volatile";
490  }
491 
492  argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
493 
494  // Get image access qualifier:
495  if (ty->isImageType()) {
496  const OpenCLImageAccessAttr *A = parm->getAttr<OpenCLImageAccessAttr>();
497  if (A && A->isWriteOnly())
498  accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
499  else
500  accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
501  // FIXME: what about read_write?
502  } else
503  accessQuals.push_back(llvm::MDString::get(Context, "none"));
504 
505  // Get argument name.
506  argNames.push_back(llvm::MDString::get(Context, parm->getName()));
507  }
508 
509  kernelMDArgs.push_back(llvm::MDNode::get(Context, addressQuals));
510  kernelMDArgs.push_back(llvm::MDNode::get(Context, accessQuals));
511  kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeNames));
512  kernelMDArgs.push_back(llvm::MDNode::get(Context, argBaseTypeNames));
513  kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeQuals));
514  if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
515  kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames));
516 }
517 
518 void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
519  llvm::Function *Fn)
520 {
521  if (!FD->hasAttr<OpenCLKernelAttr>())
522  return;
523 
524  llvm::LLVMContext &Context = getLLVMContext();
525 
527  kernelMDArgs.push_back(llvm::ConstantAsMetadata::get(Fn));
528 
529  GenOpenCLArgMetadata(FD, Fn, CGM, Context, kernelMDArgs, Builder,
530  getContext());
531 
532  if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
533  QualType hintQTy = A->getTypeHint();
534  const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
535  bool isSignedInteger =
536  hintQTy->isSignedIntegerType() ||
537  (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
538  llvm::Metadata *attrMDArgs[] = {
539  llvm::MDString::get(Context, "vec_type_hint"),
540  llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
541  CGM.getTypes().ConvertType(A->getTypeHint()))),
542  llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
543  llvm::IntegerType::get(Context, 32),
544  llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))))};
545  kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
546  }
547 
548  if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
549  llvm::Metadata *attrMDArgs[] = {
550  llvm::MDString::get(Context, "work_group_size_hint"),
551  llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
552  llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
553  llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
554  kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
555  }
556 
557  if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
558  llvm::Metadata *attrMDArgs[] = {
559  llvm::MDString::get(Context, "reqd_work_group_size"),
560  llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
561  llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
562  llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
563  kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
564  }
565 
566  llvm::MDNode *kernelMDNode = llvm::MDNode::get(Context, kernelMDArgs);
567  llvm::NamedMDNode *OpenCLKernelMetadata =
568  CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
569  OpenCLKernelMetadata->addOperand(kernelMDNode);
570 }
571 
572 /// Determine whether the function F ends with a return stmt.
573 static bool endsWithReturn(const Decl* F) {
574  const Stmt *Body = nullptr;
575  if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
576  Body = FD->getBody();
577  else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
578  Body = OMD->getBody();
579 
580  if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
581  auto LastStmt = CS->body_rbegin();
582  if (LastStmt != CS->body_rend())
583  return isa<ReturnStmt>(*LastStmt);
584  }
585  return false;
586 }
587 
589  QualType RetTy,
590  llvm::Function *Fn,
591  const CGFunctionInfo &FnInfo,
592  const FunctionArgList &Args,
593  SourceLocation Loc,
594  SourceLocation StartLoc) {
595  assert(!CurFn &&
596  "Do not use a CodeGenFunction object for more than one function");
597 
598  const Decl *D = GD.getDecl();
599 
600  DidCallStackSave = false;
601  CurCodeDecl = D;
602  CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
603  FnRetTy = RetTy;
604  CurFn = Fn;
605  CurFnInfo = &FnInfo;
606  assert(CurFn->isDeclaration() && "Function already has body?");
607 
608  if (CGM.isInSanitizerBlacklist(Fn, Loc))
609  SanOpts.clear();
610 
611  if (D) {
612  // Apply the no_sanitize* attributes to SanOpts.
613  for (auto Attr : D->specific_attrs<NoSanitizeAttr>())
614  SanOpts.Mask &= ~Attr->getMask();
615  }
616 
617  // Apply sanitizer attributes to the function.
618  if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
619  Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
620  if (SanOpts.has(SanitizerKind::Thread))
621  Fn->addFnAttr(llvm::Attribute::SanitizeThread);
622  if (SanOpts.has(SanitizerKind::Memory))
623  Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
624  if (SanOpts.has(SanitizerKind::SafeStack))
625  Fn->addFnAttr(llvm::Attribute::SafeStack);
626 
627  // Pass inline keyword to optimizer if it appears explicitly on any
628  // declaration. Also, in the case of -fno-inline attach NoInline
629  // attribute to all function that are not marked AlwaysInline.
630  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
631  if (!CGM.getCodeGenOpts().NoInline) {
632  for (auto RI : FD->redecls())
633  if (RI->isInlineSpecified()) {
634  Fn->addFnAttr(llvm::Attribute::InlineHint);
635  break;
636  }
637  } else if (!FD->hasAttr<AlwaysInlineAttr>())
638  Fn->addFnAttr(llvm::Attribute::NoInline);
639  }
640 
641  if (getLangOpts().OpenCL) {
642  // Add metadata for a kernel function.
643  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
644  EmitOpenCLKernelMetadata(FD, Fn);
645  }
646 
647  // If we are checking function types, emit a function type signature as
648  // prologue data.
649  if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
650  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
651  if (llvm::Constant *PrologueSig =
653  llvm::Constant *FTRTTIConst =
654  CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
655  llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst };
656  llvm::Constant *PrologueStructConst =
657  llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
658  Fn->setPrologueData(PrologueStructConst);
659  }
660  }
661  }
662 
663  llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
664 
665  // Create a marker to make it easy to insert allocas into the entryblock
666  // later. Don't create this with the builder, because we don't want it
667  // folded.
668  llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
669  AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
670  if (Builder.isNamePreserving())
671  AllocaInsertPt->setName("allocapt");
672 
674 
675  Builder.SetInsertPoint(EntryBB);
676 
677  // Emit subprogram debug descriptor.
678  if (CGDebugInfo *DI = getDebugInfo()) {
679  SmallVector<QualType, 16> ArgTypes;
680  for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
681  i != e; ++i) {
682  ArgTypes.push_back((*i)->getType());
683  }
684 
685  QualType FnType =
686  getContext().getFunctionType(RetTy, ArgTypes,
688  DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder);
689  }
690 
692  EmitFunctionInstrumentation("__cyg_profile_func_enter");
693 
694  if (CGM.getCodeGenOpts().InstrumentForProfiling)
696 
697  if (RetTy->isVoidType()) {
698  // Void type; nothing to return.
699  ReturnValue = nullptr;
700 
701  // Count the implicit return.
702  if (!endsWithReturn(D))
703  ++NumReturnExprs;
706  // Indirect aggregate return; emit returned value directly into sret slot.
707  // This reduces code size, and affects correctness in C++.
708  auto AI = CurFn->arg_begin();
710  ++AI;
711  ReturnValue = AI;
714  // Load the sret pointer from the argument struct and return into that.
715  unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
716  llvm::Function::arg_iterator EI = CurFn->arg_end();
717  --EI;
718  llvm::Value *Addr = Builder.CreateStructGEP(nullptr, EI, Idx);
719  ReturnValue = Builder.CreateLoad(Addr, "agg.result");
720  } else {
721  ReturnValue = CreateIRTemp(RetTy, "retval");
722 
723  // Tell the epilog emitter to autorelease the result. We do this
724  // now so that various specialized functions can suppress it
725  // during their IR-generation.
726  if (getLangOpts().ObjCAutoRefCount &&
728  RetTy->isObjCRetainableType())
729  AutoreleaseResult = true;
730  }
731 
733 
736 
737  if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
739  const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
740  if (MD->getParent()->isLambda() &&
741  MD->getOverloadedOperator() == OO_Call) {
742  // We're in a lambda; figure out the captures.
746  // If this lambda captures this, load it.
748  CXXThisValue = EmitLoadOfLValue(ThisLValue,
750  }
751  for (auto *FD : MD->getParent()->fields()) {
752  if (FD->hasCapturedVLAType()) {
753  auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
755  auto VAT = FD->getCapturedVLAType();
756  VLASizeMap[VAT->getSizeExpr()] = ExprArg;
757  }
758  }
759  } else {
760  // Not in a lambda; just use 'this' from the method.
761  // FIXME: Should we generate a new load for each use of 'this'? The
762  // fast register allocator would be happier...
763  CXXThisValue = CXXABIThisValue;
764  }
765  }
766 
767  // If any of the arguments have a variably modified type, make sure to
768  // emit the type size.
769  for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
770  i != e; ++i) {
771  const VarDecl *VD = *i;
772 
773  // Dig out the type as written from ParmVarDecls; it's unclear whether
774  // the standard (C99 6.9.1p10) requires this, but we're following the
775  // precedent set by gcc.
776  QualType Ty;
777  if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
778  Ty = PVD->getOriginalType();
779  else
780  Ty = VD->getType();
781 
782  if (Ty->isVariablyModifiedType())
784  }
785  // Emit a location at the end of the prologue.
786  if (CGDebugInfo *DI = getDebugInfo())
787  DI->EmitLocation(Builder, StartLoc);
788 }
789 
791  const Stmt *Body) {
793  if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
795  else
796  EmitStmt(Body);
797 }
798 
799 /// When instrumenting to collect profile data, the counts for some blocks
800 /// such as switch cases need to not include the fall-through counts, so
801 /// emit a branch around the instrumentation code. When not instrumenting,
802 /// this just calls EmitBlock().
804  const Stmt *S) {
805  llvm::BasicBlock *SkipCountBB = nullptr;
806  if (HaveInsertPoint() && CGM.getCodeGenOpts().ProfileInstrGenerate) {
807  // When instrumenting for profiling, the fallthrough to certain
808  // statements needs to skip over the instrumentation code so that we
809  // get an accurate count.
810  SkipCountBB = createBasicBlock("skipcount");
811  EmitBranch(SkipCountBB);
812  }
813  EmitBlock(BB);
814  uint64_t CurrentCount = getCurrentProfileCount();
817  if (SkipCountBB)
818  EmitBlock(SkipCountBB);
819 }
820 
821 /// Tries to mark the given function nounwind based on the
822 /// non-existence of any throwing calls within it. We believe this is
823 /// lightweight enough to do at -O0.
824 static void TryMarkNoThrow(llvm::Function *F) {
825  // LLVM treats 'nounwind' on a function as part of the type, so we
826  // can't do this on functions that can be overwritten.
827  if (F->mayBeOverridden()) return;
828 
829  for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
830  for (llvm::BasicBlock::iterator
831  BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
832  if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) {
833  if (!Call->doesNotThrow())
834  return;
835  } else if (isa<llvm::ResumeInst>(&*BI)) {
836  return;
837  }
838  F->setDoesNotThrow();
839 }
840 
841 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
842  const CGFunctionInfo &FnInfo) {
843  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
844 
845  // Check if we should generate debug info for this function.
846  if (FD->hasAttr<NoDebugAttr>())
847  DebugInfo = nullptr; // disable debug info indefinitely for this function
848 
849  FunctionArgList Args;
850  QualType ResTy = FD->getReturnType();
851 
852  CurGD = GD;
853  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
854  if (MD && MD->isInstance()) {
855  if (CGM.getCXXABI().HasThisReturn(GD))
856  ResTy = MD->getThisType(getContext());
857  else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
858  ResTy = CGM.getContext().VoidPtrTy;
859  CGM.getCXXABI().buildThisParam(*this, Args);
860  }
861 
862  Args.append(FD->param_begin(), FD->param_end());
863 
864  if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
865  CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
866 
867  SourceRange BodyRange;
868  if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
869  CurEHLocation = BodyRange.getEnd();
870 
871  // Use the location of the start of the function to determine where
872  // the function definition is located. By default use the location
873  // of the declaration as the location for the subprogram. A function
874  // may lack a declaration in the source code if it is created by code
875  // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
876  SourceLocation Loc = FD->getLocation();
877 
878  // If this is a function specialization then use the pattern body
879  // as the location for the function.
880  if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
881  if (SpecDecl->hasBody(SpecDecl))
882  Loc = SpecDecl->getLocation();
883 
884  // Emit the standard function prologue.
885  StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
886 
887  // Generate the body of the function.
888  PGO.checkGlobalDecl(GD);
890  if (isa<CXXDestructorDecl>(FD))
891  EmitDestructorBody(Args);
892  else if (isa<CXXConstructorDecl>(FD))
893  EmitConstructorBody(Args);
894  else if (getLangOpts().CUDA &&
895  !getLangOpts().CUDAIsDevice &&
896  FD->hasAttr<CUDAGlobalAttr>())
897  CGM.getCUDARuntime().emitDeviceStub(*this, Args);
898  else if (isa<CXXConversionDecl>(FD) &&
899  cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
900  // The lambda conversion to block pointer is special; the semantics can't be
901  // expressed in the AST, so IRGen needs to special-case it.
903  } else if (isa<CXXMethodDecl>(FD) &&
904  cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
905  // The lambda static invoker function is special, because it forwards or
906  // clones the body of the function call operator (but is actually static).
907  EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
908  } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
909  (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
910  cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
911  // Implicit copy-assignment gets the same special treatment as implicit
912  // copy-constructors.
914  } else if (Stmt *Body = FD->getBody()) {
915  EmitFunctionBody(Args, Body);
916  } else
917  llvm_unreachable("no definition for emitted function");
918 
919  // C++11 [stmt.return]p2:
920  // Flowing off the end of a function [...] results in undefined behavior in
921  // a value-returning function.
922  // C11 6.9.1p12:
923  // If the '}' that terminates a function is reached, and the value of the
924  // function call is used by the caller, the behavior is undefined.
926  !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
927  if (SanOpts.has(SanitizerKind::Return)) {
928  SanitizerScope SanScope(this);
929  llvm::Value *IsFalse = Builder.getFalse();
930  EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
931  "missing_return", EmitCheckSourceLocation(FD->getLocation()),
932  None);
933  } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
934  EmitTrapCall(llvm::Intrinsic::trap);
935  }
936  Builder.CreateUnreachable();
937  Builder.ClearInsertionPoint();
938  }
939 
940  // Emit the standard function epilogue.
941  FinishFunction(BodyRange.getEnd());
942 
943  // If we haven't marked the function nothrow through other means, do
944  // a quick pass now to see if we can.
945  if (!CurFn->doesNotThrow())
947 }
948 
949 /// ContainsLabel - Return true if the statement contains a label in it. If
950 /// this statement is not executed normally, it not containing a label means
951 /// that we can just remove the code.
952 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
953  // Null statement, not a label!
954  if (!S) return false;
955 
956  // If this is a label, we have to emit the code, consider something like:
957  // if (0) { ... foo: bar(); } goto foo;
958  //
959  // TODO: If anyone cared, we could track __label__'s, since we know that you
960  // can't jump to one from outside their declared region.
961  if (isa<LabelStmt>(S))
962  return true;
963 
964  // If this is a case/default statement, and we haven't seen a switch, we have
965  // to emit the code.
966  if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
967  return true;
968 
969  // If this is a switch statement, we want to ignore cases below it.
970  if (isa<SwitchStmt>(S))
971  IgnoreCaseStmts = true;
972 
973  // Scan subexpressions for verboten labels.
974  for (const Stmt *SubStmt : S->children())
975  if (ContainsLabel(SubStmt, IgnoreCaseStmts))
976  return true;
977 
978  return false;
979 }
980 
981 /// containsBreak - Return true if the statement contains a break out of it.
982 /// If the statement (recursively) contains a switch or loop with a break
983 /// inside of it, this is fine.
985  // Null statement, not a label!
986  if (!S) return false;
987 
988  // If this is a switch or loop that defines its own break scope, then we can
989  // include it and anything inside of it.
990  if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
991  isa<ForStmt>(S))
992  return false;
993 
994  if (isa<BreakStmt>(S))
995  return true;
996 
997  // Scan subexpressions for verboten breaks.
998  for (const Stmt *SubStmt : S->children())
999  if (containsBreak(SubStmt))
1000  return true;
1001 
1002  return false;
1003 }
1004 
1005 
1006 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1007 /// to a constant, or if it does but contains a label, return false. If it
1008 /// constant folds return true and set the boolean result in Result.
1010  bool &ResultBool) {
1011  llvm::APSInt ResultInt;
1012  if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
1013  return false;
1014 
1015  ResultBool = ResultInt.getBoolValue();
1016  return true;
1017 }
1018 
1019 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1020 /// to a constant, or if it does but contains a label, return false. If it
1021 /// constant folds return true and set the folded value.
1022 bool CodeGenFunction::
1023 ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &ResultInt) {
1024  // FIXME: Rename and handle conversion of other evaluatable things
1025  // to bool.
1026  llvm::APSInt Int;
1027  if (!Cond->EvaluateAsInt(Int, getContext()))
1028  return false; // Not foldable, not integer or not fully evaluatable.
1029 
1031  return false; // Contains a label.
1032 
1033  ResultInt = Int;
1034  return true;
1035 }
1036 
1037 
1038 
1039 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1040 /// statement) to the specified blocks. Based on the condition, this might try
1041 /// to simplify the codegen of the conditional based on the branch.
1042 ///
1044  llvm::BasicBlock *TrueBlock,
1045  llvm::BasicBlock *FalseBlock,
1046  uint64_t TrueCount) {
1047  Cond = Cond->IgnoreParens();
1048 
1049  if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1050 
1051  // Handle X && Y in a condition.
1052  if (CondBOp->getOpcode() == BO_LAnd) {
1053  // If we have "1 && X", simplify the code. "0 && X" would have constant
1054  // folded if the case was simple enough.
1055  bool ConstantBool = false;
1056  if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1057  ConstantBool) {
1058  // br(1 && X) -> br(X).
1059  incrementProfileCounter(CondBOp);
1060  return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1061  TrueCount);
1062  }
1063 
1064  // If we have "X && 1", simplify the code to use an uncond branch.
1065  // "X && 0" would have been constant folded to 0.
1066  if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1067  ConstantBool) {
1068  // br(X && 1) -> br(X).
1069  return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1070  TrueCount);
1071  }
1072 
1073  // Emit the LHS as a conditional. If the LHS conditional is false, we
1074  // want to jump to the FalseBlock.
1075  llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
1076  // The counter tells us how often we evaluate RHS, and all of TrueCount
1077  // can be propagated to that branch.
1078  uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
1079 
1080  ConditionalEvaluation eval(*this);
1081  {
1082  ApplyDebugLocation DL(*this, Cond);
1083  EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
1084  EmitBlock(LHSTrue);
1085  }
1086 
1087  incrementProfileCounter(CondBOp);
1088  setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1089 
1090  // Any temporaries created here are conditional.
1091  eval.begin(*this);
1092  EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
1093  eval.end(*this);
1094 
1095  return;
1096  }
1097 
1098  if (CondBOp->getOpcode() == BO_LOr) {
1099  // If we have "0 || X", simplify the code. "1 || X" would have constant
1100  // folded if the case was simple enough.
1101  bool ConstantBool = false;
1102  if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1103  !ConstantBool) {
1104  // br(0 || X) -> br(X).
1105  incrementProfileCounter(CondBOp);
1106  return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1107  TrueCount);
1108  }
1109 
1110  // If we have "X || 0", simplify the code to use an uncond branch.
1111  // "X || 1" would have been constant folded to 1.
1112  if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1113  !ConstantBool) {
1114  // br(X || 0) -> br(X).
1115  return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1116  TrueCount);
1117  }
1118 
1119  // Emit the LHS as a conditional. If the LHS conditional is true, we
1120  // want to jump to the TrueBlock.
1121  llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
1122  // We have the count for entry to the RHS and for the whole expression
1123  // being true, so we can divy up True count between the short circuit and
1124  // the RHS.
1125  uint64_t LHSCount =
1126  getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
1127  uint64_t RHSCount = TrueCount - LHSCount;
1128 
1129  ConditionalEvaluation eval(*this);
1130  {
1131  ApplyDebugLocation DL(*this, Cond);
1132  EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
1133  EmitBlock(LHSFalse);
1134  }
1135 
1136  incrementProfileCounter(CondBOp);
1137  setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1138 
1139  // Any temporaries created here are conditional.
1140  eval.begin(*this);
1141  EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
1142 
1143  eval.end(*this);
1144 
1145  return;
1146  }
1147  }
1148 
1149  if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1150  // br(!x, t, f) -> br(x, f, t)
1151  if (CondUOp->getOpcode() == UO_LNot) {
1152  // Negate the count.
1153  uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
1154  // Negate the condition and swap the destination blocks.
1155  return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1156  FalseCount);
1157  }
1158  }
1159 
1160  if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1161  // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1162  llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1163  llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1164 
1165  ConditionalEvaluation cond(*this);
1166  EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
1167  getProfileCount(CondOp));
1168 
1169  // When computing PGO branch weights, we only know the overall count for
1170  // the true block. This code is essentially doing tail duplication of the
1171  // naive code-gen, introducing new edges for which counts are not
1172  // available. Divide the counts proportionally between the LHS and RHS of
1173  // the conditional operator.
1174  uint64_t LHSScaledTrueCount = 0;
1175  if (TrueCount) {
1176  double LHSRatio =
1177  getProfileCount(CondOp) / (double)getCurrentProfileCount();
1178  LHSScaledTrueCount = TrueCount * LHSRatio;
1179  }
1180 
1181  cond.begin(*this);
1182  EmitBlock(LHSBlock);
1183  incrementProfileCounter(CondOp);
1184  {
1185  ApplyDebugLocation DL(*this, Cond);
1186  EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
1187  LHSScaledTrueCount);
1188  }
1189  cond.end(*this);
1190 
1191  cond.begin(*this);
1192  EmitBlock(RHSBlock);
1193  EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
1194  TrueCount - LHSScaledTrueCount);
1195  cond.end(*this);
1196 
1197  return;
1198  }
1199 
1200  if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1201  // Conditional operator handling can give us a throw expression as a
1202  // condition for a case like:
1203  // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1204  // Fold this to:
1205  // br(c, throw x, br(y, t, f))
1206  EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1207  return;
1208  }
1209 
1210  // Create branch weights based on the number of times we get here and the
1211  // number of times the condition should be true.
1212  uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
1213  llvm::MDNode *Weights =
1214  createProfileWeights(TrueCount, CurrentCount - TrueCount);
1215 
1216  // Emit the code with the fully general case.
1217  llvm::Value *CondV;
1218  {
1219  ApplyDebugLocation DL(*this, Cond);
1220  CondV = EvaluateExprAsBool(Cond);
1221  }
1222  Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights);
1223 }
1224 
1225 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1226 /// specified stmt yet.
1227 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1228  CGM.ErrorUnsupported(S, Type);
1229 }
1230 
1231 /// emitNonZeroVLAInit - Emit the "zero" initialization of a
1232 /// variable-length array whose elements have a non-zero bit-pattern.
1233 ///
1234 /// \param baseType the inner-most element type of the array
1235 /// \param src - a char* pointing to the bit-pattern for a single
1236 /// base element of the array
1237 /// \param sizeInChars - the total size of the VLA, in chars
1238 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
1239  llvm::Value *dest, llvm::Value *src,
1240  llvm::Value *sizeInChars) {
1241  std::pair<CharUnits,CharUnits> baseSizeAndAlign
1242  = CGF.getContext().getTypeInfoInChars(baseType);
1243 
1244  CGBuilderTy &Builder = CGF.Builder;
1245 
1246  llvm::Value *baseSizeInChars
1247  = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
1248 
1249  llvm::Type *i8p = Builder.getInt8PtrTy();
1250 
1251  llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
1252  llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
1253 
1254  llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
1255  llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
1256  llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
1257 
1258  // Make a loop over the VLA. C99 guarantees that the VLA element
1259  // count must be nonzero.
1260  CGF.EmitBlock(loopBB);
1261 
1262  llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur");
1263  cur->addIncoming(begin, originBB);
1264 
1265  // memcpy the individual element bit-pattern.
1266  Builder.CreateMemCpy(cur, src, baseSizeInChars,
1267  baseSizeAndAlign.second.getQuantity(),
1268  /*volatile*/ false);
1269 
1270  // Go to the next element.
1271  llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(),
1272  cur, 1, "vla.next");
1273 
1274  // Leave if that's the end of the VLA.
1275  llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
1276  Builder.CreateCondBr(done, contBB, loopBB);
1277  cur->addIncoming(next, loopBB);
1278 
1279  CGF.EmitBlock(contBB);
1280 }
1281 
1282 void
1284  // Ignore empty classes in C++.
1285  if (getLangOpts().CPlusPlus) {
1286  if (const RecordType *RT = Ty->getAs<RecordType>()) {
1287  if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1288  return;
1289  }
1290  }
1291 
1292  // Cast the dest ptr to the appropriate i8 pointer type.
1293  unsigned DestAS =
1294  cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
1295  llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
1296  if (DestPtr->getType() != BP)
1297  DestPtr = Builder.CreateBitCast(DestPtr, BP);
1298 
1299  // Get size and alignment info for this aggregate.
1300  std::pair<CharUnits, CharUnits> TypeInfo =
1302  CharUnits Size = TypeInfo.first;
1303  CharUnits Align = TypeInfo.second;
1304 
1305  llvm::Value *SizeVal;
1306  const VariableArrayType *vla;
1307 
1308  // Don't bother emitting a zero-byte memset.
1309  if (Size.isZero()) {
1310  // But note that getTypeInfo returns 0 for a VLA.
1311  if (const VariableArrayType *vlaType =
1312  dyn_cast_or_null<VariableArrayType>(
1313  getContext().getAsArrayType(Ty))) {
1314  QualType eltType;
1315  llvm::Value *numElts;
1316  std::tie(numElts, eltType) = getVLASize(vlaType);
1317 
1318  SizeVal = numElts;
1319  CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
1320  if (!eltSize.isOne())
1321  SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
1322  vla = vlaType;
1323  } else {
1324  return;
1325  }
1326  } else {
1327  SizeVal = CGM.getSize(Size);
1328  vla = nullptr;
1329  }
1330 
1331  // If the type contains a pointer to data member we can't memset it to zero.
1332  // Instead, create a null constant and copy it to the destination.
1333  // TODO: there are other patterns besides zero that we can usefully memset,
1334  // like -1, which happens to be the pattern used by member-pointers.
1335  if (!CGM.getTypes().isZeroInitializable(Ty)) {
1336  // For a VLA, emit a single element, then splat that over the VLA.
1337  if (vla) Ty = getContext().getBaseElementType(vla);
1338 
1339  llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1340 
1341  llvm::GlobalVariable *NullVariable =
1342  new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1343  /*isConstant=*/true,
1344  llvm::GlobalVariable::PrivateLinkage,
1345  NullConstant, Twine());
1346  llvm::Value *SrcPtr =
1347  Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
1348 
1349  if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
1350 
1351  // Get and call the appropriate llvm.memcpy overload.
1352  Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false);
1353  return;
1354  }
1355 
1356  // Otherwise, just memset the whole thing to zero. This is legal
1357  // because in LLVM, all default initializers (other than the ones we just
1358  // handled above) are guaranteed to have a bit pattern of all zeros.
1359  Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal,
1360  Align.getQuantity(), false);
1361 }
1362 
1363 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
1364  // Make sure that there is a block for the indirect goto.
1365  if (!IndirectBranch)
1367 
1368  llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
1369 
1370  // Make sure the indirect branch includes all of the address-taken blocks.
1371  IndirectBranch->addDestination(BB);
1372  return llvm::BlockAddress::get(CurFn, BB);
1373 }
1374 
1376  // If we already made the indirect branch for indirect goto, return its block.
1377  if (IndirectBranch) return IndirectBranch->getParent();
1378 
1379  CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
1380 
1381  // Create the PHI node that indirect gotos will add entries to.
1382  llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
1383  "indirect.goto.dest");
1384 
1385  // Create the indirect branch instruction.
1386  IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1387  return IndirectBranch->getParent();
1388 }
1389 
1390 /// Computes the length of an array in elements, as well as the base
1391 /// element type and a properly-typed first element pointer.
1393  QualType &baseType,
1394  llvm::Value *&addr) {
1395  const ArrayType *arrayType = origArrayType;
1396 
1397  // If it's a VLA, we have to load the stored size. Note that
1398  // this is the size of the VLA in bytes, not its size in elements.
1399  llvm::Value *numVLAElements = nullptr;
1400  if (isa<VariableArrayType>(arrayType)) {
1401  numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
1402 
1403  // Walk into all VLAs. This doesn't require changes to addr,
1404  // which has type T* where T is the first non-VLA element type.
1405  do {
1406  QualType elementType = arrayType->getElementType();
1407  arrayType = getContext().getAsArrayType(elementType);
1408 
1409  // If we only have VLA components, 'addr' requires no adjustment.
1410  if (!arrayType) {
1411  baseType = elementType;
1412  return numVLAElements;
1413  }
1414  } while (isa<VariableArrayType>(arrayType));
1415 
1416  // We get out here only if we find a constant array type
1417  // inside the VLA.
1418  }
1419 
1420  // We have some number of constant-length arrays, so addr should
1421  // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
1422  // down to the first element of addr.
1423  SmallVector<llvm::Value*, 8> gepIndices;
1424 
1425  // GEP down to the array type.
1426  llvm::ConstantInt *zero = Builder.getInt32(0);
1427  gepIndices.push_back(zero);
1428 
1429  uint64_t countFromCLAs = 1;
1430  QualType eltType;
1431 
1432  llvm::ArrayType *llvmArrayType =
1433  dyn_cast<llvm::ArrayType>(
1434  cast<llvm::PointerType>(addr->getType())->getElementType());
1435  while (llvmArrayType) {
1436  assert(isa<ConstantArrayType>(arrayType));
1437  assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
1438  == llvmArrayType->getNumElements());
1439 
1440  gepIndices.push_back(zero);
1441  countFromCLAs *= llvmArrayType->getNumElements();
1442  eltType = arrayType->getElementType();
1443 
1444  llvmArrayType =
1445  dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
1446  arrayType = getContext().getAsArrayType(arrayType->getElementType());
1447  assert((!llvmArrayType || arrayType) &&
1448  "LLVM and Clang types are out-of-synch");
1449  }
1450 
1451  if (arrayType) {
1452  // From this point onwards, the Clang array type has been emitted
1453  // as some other type (probably a packed struct). Compute the array
1454  // size, and just emit the 'begin' expression as a bitcast.
1455  while (arrayType) {
1456  countFromCLAs *=
1457  cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
1458  eltType = arrayType->getElementType();
1459  arrayType = getContext().getAsArrayType(eltType);
1460  }
1461 
1462  unsigned AddressSpace = addr->getType()->getPointerAddressSpace();
1463  llvm::Type *BaseType = ConvertType(eltType)->getPointerTo(AddressSpace);
1464  addr = Builder.CreateBitCast(addr, BaseType, "array.begin");
1465  } else {
1466  // Create the actual GEP.
1467  addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin");
1468  }
1469 
1470  baseType = eltType;
1471 
1472  llvm::Value *numElements
1473  = llvm::ConstantInt::get(SizeTy, countFromCLAs);
1474 
1475  // If we had any VLA dimensions, factor them in.
1476  if (numVLAElements)
1477  numElements = Builder.CreateNUWMul(numVLAElements, numElements);
1478 
1479  return numElements;
1480 }
1481 
1482 std::pair<llvm::Value*, QualType>
1485  assert(vla && "type was not a variable array type!");
1486  return getVLASize(vla);
1487 }
1488 
1489 std::pair<llvm::Value*, QualType>
1491  // The number of elements so far; always size_t.
1492  llvm::Value *numElements = nullptr;
1493 
1494  QualType elementType;
1495  do {
1496  elementType = type->getElementType();
1497  llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
1498  assert(vlaSize && "no size for VLA!");
1499  assert(vlaSize->getType() == SizeTy);
1500 
1501  if (!numElements) {
1502  numElements = vlaSize;
1503  } else {
1504  // It's undefined behavior if this wraps around, so mark it that way.
1505  // FIXME: Teach -fsanitize=undefined to trap this.
1506  numElements = Builder.CreateNUWMul(numElements, vlaSize);
1507  }
1508  } while ((type = getContext().getAsVariableArrayType(elementType)));
1509 
1510  return std::pair<llvm::Value*,QualType>(numElements, elementType);
1511 }
1512 
1514  assert(type->isVariablyModifiedType() &&
1515  "Must pass variably modified type to EmitVLASizes!");
1516 
1518 
1519  // We're going to walk down into the type and look for VLA
1520  // expressions.
1521  do {
1522  assert(type->isVariablyModifiedType());
1523 
1524  const Type *ty = type.getTypePtr();
1525  switch (ty->getTypeClass()) {
1526 
1527 #define TYPE(Class, Base)
1528 #define ABSTRACT_TYPE(Class, Base)
1529 #define NON_CANONICAL_TYPE(Class, Base)
1530 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1531 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
1532 #include "clang/AST/TypeNodes.def"
1533  llvm_unreachable("unexpected dependent type!");
1534 
1535  // These types are never variably-modified.
1536  case Type::Builtin:
1537  case Type::Complex:
1538  case Type::Vector:
1539  case Type::ExtVector:
1540  case Type::Record:
1541  case Type::Enum:
1542  case Type::Elaborated:
1543  case Type::TemplateSpecialization:
1544  case Type::ObjCObject:
1545  case Type::ObjCInterface:
1546  case Type::ObjCObjectPointer:
1547  llvm_unreachable("type class is never variably-modified!");
1548 
1549  case Type::Adjusted:
1550  type = cast<AdjustedType>(ty)->getAdjustedType();
1551  break;
1552 
1553  case Type::Decayed:
1554  type = cast<DecayedType>(ty)->getPointeeType();
1555  break;
1556 
1557  case Type::Pointer:
1558  type = cast<PointerType>(ty)->getPointeeType();
1559  break;
1560 
1561  case Type::BlockPointer:
1562  type = cast<BlockPointerType>(ty)->getPointeeType();
1563  break;
1564 
1565  case Type::LValueReference:
1566  case Type::RValueReference:
1567  type = cast<ReferenceType>(ty)->getPointeeType();
1568  break;
1569 
1570  case Type::MemberPointer:
1571  type = cast<MemberPointerType>(ty)->getPointeeType();
1572  break;
1573 
1574  case Type::ConstantArray:
1575  case Type::IncompleteArray:
1576  // Losing element qualification here is fine.
1577  type = cast<ArrayType>(ty)->getElementType();
1578  break;
1579 
1580  case Type::VariableArray: {
1581  // Losing element qualification here is fine.
1582  const VariableArrayType *vat = cast<VariableArrayType>(ty);
1583 
1584  // Unknown size indication requires no size computation.
1585  // Otherwise, evaluate and record it.
1586  if (const Expr *size = vat->getSizeExpr()) {
1587  // It's possible that we might have emitted this already,
1588  // e.g. with a typedef and a pointer to it.
1589  llvm::Value *&entry = VLASizeMap[size];
1590  if (!entry) {
1591  llvm::Value *Size = EmitScalarExpr(size);
1592 
1593  // C11 6.7.6.2p5:
1594  // If the size is an expression that is not an integer constant
1595  // expression [...] each time it is evaluated it shall have a value
1596  // greater than zero.
1597  if (SanOpts.has(SanitizerKind::VLABound) &&
1598  size->getType()->isSignedIntegerType()) {
1599  SanitizerScope SanScope(this);
1600  llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
1601  llvm::Constant *StaticArgs[] = {
1602  EmitCheckSourceLocation(size->getLocStart()),
1603  EmitCheckTypeDescriptor(size->getType())
1604  };
1605  EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
1606  SanitizerKind::VLABound),
1607  "vla_bound_not_positive", StaticArgs, Size);
1608  }
1609 
1610  // Always zexting here would be wrong if it weren't
1611  // undefined behavior to have a negative bound.
1612  entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
1613  }
1614  }
1615  type = vat->getElementType();
1616  break;
1617  }
1618 
1619  case Type::FunctionProto:
1620  case Type::FunctionNoProto:
1621  type = cast<FunctionType>(ty)->getReturnType();
1622  break;
1623 
1624  case Type::Paren:
1625  case Type::TypeOf:
1626  case Type::UnaryTransform:
1627  case Type::Attributed:
1628  case Type::SubstTemplateTypeParm:
1629  case Type::PackExpansion:
1630  // Keep walking after single level desugaring.
1631  type = type.getSingleStepDesugaredType(getContext());
1632  break;
1633 
1634  case Type::Typedef:
1635  case Type::Decltype:
1636  case Type::Auto:
1637  // Stop walking: nothing to do.
1638  return;
1639 
1640  case Type::TypeOfExpr:
1641  // Stop walking: emit typeof expression.
1642  EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
1643  return;
1644 
1645  case Type::Atomic:
1646  type = cast<AtomicType>(ty)->getValueType();
1647  break;
1648  }
1649  } while (type->isVariablyModifiedType());
1650 }
1651 
1653  if (getContext().getBuiltinVaListType()->isArrayType())
1654  return EmitScalarExpr(E);
1655  return EmitLValue(E).getAddress();
1656 }
1657 
1659  llvm::Constant *Init) {
1660  assert (Init && "Invalid DeclRefExpr initializer!");
1661  if (CGDebugInfo *Dbg = getDebugInfo())
1662  if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
1663  Dbg->EmitGlobalVariable(E->getDecl(), Init);
1664 }
1665 
1668  // At the moment, the only aggressive peephole we do in IR gen
1669  // is trunc(zext) folding, but if we add more, we can easily
1670  // extend this protection.
1671 
1672  if (!rvalue.isScalar()) return PeepholeProtection();
1673  llvm::Value *value = rvalue.getScalarVal();
1674  if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
1675 
1676  // Just make an extra bitcast.
1677  assert(HaveInsertPoint());
1678  llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
1679  Builder.GetInsertBlock());
1680 
1681  PeepholeProtection protection;
1682  protection.Inst = inst;
1683  return protection;
1684 }
1685 
1687  if (!protection.Inst) return;
1688 
1689  // In theory, we could try to duplicate the peepholes now, but whatever.
1690  protection.Inst->eraseFromParent();
1691 }
1692 
1694  llvm::Value *AnnotatedVal,
1695  StringRef AnnotationStr,
1696  SourceLocation Location) {
1697  llvm::Value *Args[4] = {
1698  AnnotatedVal,
1699  Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
1700  Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
1701  CGM.EmitAnnotationLineNo(Location)
1702  };
1703  return Builder.CreateCall(AnnotationFn, Args);
1704 }
1705 
1707  assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1708  // FIXME We create a new bitcast for every annotation because that's what
1709  // llvm-gcc was doing.
1710  for (const auto *I : D->specific_attrs<AnnotateAttr>())
1711  EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
1712  Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
1713  I->getAnnotation(), D->getLocation());
1714 }
1715 
1717  llvm::Value *V) {
1718  assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1719  llvm::Type *VTy = V->getType();
1720  llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
1721  CGM.Int8PtrTy);
1722 
1723  for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
1724  // FIXME Always emit the cast inst so we can differentiate between
1725  // annotation on the first field of a struct and annotation on the struct
1726  // itself.
1727  if (VTy != CGM.Int8PtrTy)
1728  V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
1729  V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
1730  V = Builder.CreateBitCast(V, VTy);
1731  }
1732 
1733  return V;
1734 }
1735 
1737 
1739  : CGF(CGF) {
1740  assert(!CGF->IsSanitizerScope);
1741  CGF->IsSanitizerScope = true;
1742 }
1743 
1745  CGF->IsSanitizerScope = false;
1746 }
1747 
1748 void CodeGenFunction::InsertHelper(llvm::Instruction *I,
1749  const llvm::Twine &Name,
1750  llvm::BasicBlock *BB,
1751  llvm::BasicBlock::iterator InsertPt) const {
1753  if (IsSanitizerScope)
1755 }
1756 
1757 template <bool PreserveNames>
1759  llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
1760  llvm::BasicBlock::iterator InsertPt) const {
1761  llvm::IRBuilderDefaultInserter<PreserveNames>::InsertHelper(I, Name, BB,
1762  InsertPt);
1763  if (CGF)
1764  CGF->InsertHelper(I, Name, BB, InsertPt);
1765 }
1766 
1767 #ifdef NDEBUG
1768 #define PreserveNames false
1769 #else
1770 #define PreserveNames true
1771 #endif
1773  llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
1774  llvm::BasicBlock::iterator InsertPt) const;
1775 #undef PreserveNames
unsigned getAddressSpace() const
getAddressSpace - Return the address space of this type.
Definition: Type.h:5131
Defines the clang::ASTContext interface.
SourceLocation getEnd() const
StringRef getName() const
Definition: Decl.h:168
CanQualType VoidPtrTy
Definition: ASTContext.h:831
llvm::Type * ConvertTypeForMem(QualType T)
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount)
CanQualType getReturnType() const
unsigned getInAllocaFieldIndex() const
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler...
Definition: CGExpr.cpp:2135
llvm::Module & getModule() const
void EmitFunctionInstrumentation(const char *Fn)
bool isOne() const
isOne - Test whether the quantity equals one.
Definition: CharUnits.h:119
void checkGlobalDecl(GlobalDecl GD)
Check if we need to emit coverage mapping for a given declaration.
Definition: CodeGenPGO.cpp:646
virtual void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy, FunctionArgList &Params)=0
const TargetInfo & getTarget() const
static bool endsWithReturn(const Decl *F)
Determine whether the function F ends with a return stmt.
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:163
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
std::string getAsString() const
Definition: Type.h:897
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
const LangOptions & getLangOpts() const
llvm::Value * getAddress() const
Definition: CGValue.h:265
RAII object to set/unset CodeGenFunction::IsSanitizerScope.
ExtProtoInfo - Extra information about a function prototype.
Definition: Type.h:3042
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
bool isCanonical() const
Definition: Type.h:5060
QualType getThisType(ASTContext &C) const
Returns the type of the this pointer.
Definition: DeclCXX.cpp:1592
llvm::CallInst * EmitTrapCall(llvm::Intrinsic::ID IntrID)
Emit a call to trap or debugtrap and attach function attribute "trap-func-name" if specified...
Definition: CGExpr.cpp:2418
void EmitVariablyModifiedType(QualType Ty)
void setCurrentProfileCount(uint64_t Count)
Set the profiler's current count.
bool IsSanitizerScope
True if CodeGen currently emits code implementing sanitizer checks.
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:35
bool isImageType() const
Definition: Type.h:5379
llvm::Type * ConvertTypeForMem(QualType T)
A C++ throw-expression (C++ [except.throw]).
Definition: ExprCXX.h:808
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1334
bool isObjCRetainableType() const
Definition: Type.cpp:3542
static void destroyBlockInfos(CGBlockInfo *info)
Destroy a chain of block layouts.
Definition: CGBlocks.cpp:674
void emitImplicitAssignmentOperatorBody(FunctionArgList &Args)
Definition: CGClass.cpp:1482
bool isVoidType() const
Definition: Type.h:5426
EHScopeStack::stable_iterator PrologueCleanupDepth
virtual bool hasMostDerivedReturn(GlobalDecl GD) const
Definition: CGCXXABI.h:97
JumpDest getJumpDestForLabel(const LabelDecl *S)
Definition: CGStmt.cpp:402
llvm::DenseMap< const VarDecl *, FieldDecl * > LambdaCaptureFields
An object to manage conditionally-evaluated expressions.
PeepholeProtection protectFromPeepholes(RValue rvalue)
CGBlockInfo * FirstBlockInfo
FirstBlockInfo - The head of a singly-linked-list of block layouts.
void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, SourceLocation EndLoc)
Definition: CGCall.cpp:2333
bool hasAttr() const
Definition: DeclBase.h:487
Expr * getSizeExpr() const
Definition: Type.h:2568
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:1742
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:89
LValue EmitLValueForLambdaField(const FieldDecl *Field)
Definition: CGExpr.cpp:2671
static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType, llvm::Value *dest, llvm::Value *src, llvm::Value *sizeInChars)
QualType getReturnType() const
Definition: Decl.h:1997
void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB, llvm::BasicBlock::iterator InsertPt) const
CGBuilder insert helper. This function is called after an instruction is created using Builder...
SanitizerMask Mask
Bitmask of enabled sanitizers.
Definition: Sanitizers.h:73
const Decl * getDecl() const
Definition: GlobalDecl.h:60
void disableSanitizerForInstruction(llvm::Instruction *I)
T * getAttr() const
Definition: DeclBase.h:484
virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF)=0
Emit the ABI-specific prolog for the function.
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
static bool hasScalarEvaluationKind(QualType T)
const LangOptions & getLangOpts() const
Definition: ASTContext.h:533
virtual bool isTypeInfoCalculable(QualType Ty) const
Definition: CGCXXABI.h:167
const CXXRecordDecl * getParent() const
Definition: DeclCXX.h:1817
bool isDefaulted() const
Definition: Decl.h:1805
field_range fields() const
Definition: Decl.h:3349
const ArrayType * getAsArrayType(QualType T) const
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2918
FunctionDecl * getTemplateInstantiationPattern() const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:3018
void incrementProfileCounter(const Stmt *S)
Increment the profiler's counter for the given statement.
void EmitStmt(const Stmt *S)
Definition: CGStmt.cpp:45
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
Definition: CGExpr.cpp:107
TypeClass getTypeClass() const
Definition: Type.h:1486
GlobalDecl CurGD
CurGD - The GlobalDecl for the current function being compiled.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
llvm::DebugLoc EmitReturnBlock()
Emit the unified return block, trying to avoid its emission when possible.
virtual void emitDeviceStub(CodeGenFunction &CGF, FunctionArgList &Args)=0
Emits a kernel launch stub.
std::pair< CharUnits, CharUnits > getTypeInfoInChars(const Type *T) const
QualType getType() const
Definition: Decl.h:538
param_iterator param_begin()
Definition: Decl.h:1947
void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init)
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerMask >> Checked, StringRef CheckName, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs)
Create a basic block that will call a handler function in a sanitizer runtime with the provided argum...
Definition: CGExpr.cpp:2295
llvm::CallInst * EmitNounwindRuntimeCall(llvm::Value *callee, const Twine &name="")
const TargetCodeGenInfo & getTargetCodeGenInfo()
void clear()
Disable all sanitizers.
Definition: Sanitizers.h:67
static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB)
ASTContext * Context
QualType getPointeeType() const
Definition: Type.cpp:414
static TypeEvaluationKind getEvaluationKind(QualType T)
llvm::Constant * EmitAnnotationUnit(SourceLocation Loc)
Emit the annotation's translation unit.
static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn, CodeGenModule &CGM, llvm::LLVMContext &Context, SmallVector< llvm::Metadata *, 5 > &kernelMDArgs, CGBuilderTy &Builder, ASTContext &ASTCtx)
llvm::BasicBlock * EHResumeBlock
EHResumeBlock - Unified block containing a call to llvm.eh.resume.
bool empty() const
Determines whether the exception-scopes stack is empty.
Definition: EHScopeStack.h:327
bool isInstance() const
Definition: DeclCXX.h:1744
CGCXXABI & getCXXABI() const
llvm::Value * emitArrayLength(const ArrayType *arrayType, QualType &baseType, llvm::Value *&addr)
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:1968
static void TryMarkNoThrow(llvm::Function *F)
ASTContext & getContext() const
llvm::BasicBlock * getBlock() const
llvm::Value * EmitCompoundStmtWithoutScope(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
Definition: CGStmt.cpp:287
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
stable_iterator stable_begin() const
Definition: EHScopeStack.h:364
llvm::LLVMContext & getLLVMContext()
llvm::BasicBlock * GetIndirectGotoBlock()
void EmitConstructorBody(FunctionArgList &Args)
EmitConstructorBody - Emits the body of the current constructor.
Definition: CGClass.cpp:797
llvm::Constant * EmitAnnotationString(StringRef Str)
Emit an annotation string.
bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
virtual llvm::Constant * getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const
virtual bool HasThisReturn(GlobalDecl GD) const
Definition: CGCXXABI.h:95
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T)
bool containsOnlyLifetimeMarkers(stable_iterator Old) const
Definition: CGCleanup.cpp:128
void EmitMCountInstrumentation()
EmitMCountInstrumentation - Emit call to .mcount.
void EmitLambdaToBlockPointerBody(FunctionArgList &Args)
Definition: CGClass.cpp:2420
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys=None)
ValueDecl * getDecl()
Definition: Expr.h:994
QualType getElementType() const
Definition: Type.h:2723
llvm::IRBuilder< PreserveNames, llvm::ConstantFolder, CGBuilderInserterTy > CGBuilderTy
Definition: CGBuilder.h:49
virtual void startNewFunction()
Definition: Mangle.h:73
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:486
Stmt * getBody(const FunctionDecl *&Definition) const
Definition: Decl.cpp:2405
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl. It will iterate at least once ...
Definition: Redeclarable.h:228
#define false
Definition: stdbool.h:33
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
bool hasOneOf(SanitizerMask K) const
Check if one or more sanitizers are enabled.
Definition: Sanitizers.h:58
llvm::Constant * CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeSet ExtraAttrs=llvm::AttributeSet())
Create a new runtime function with the specified type and name.
llvm::AllocaInst * CreateIRTemp(QualType T, const Twine &Name="tmp")
Definition: CGExpr.cpp:71
ASTContext & getContext() const
Encodes a location in the source. The SourceManager can decode this to get at the full include stack...
unsigned getNumParams() const
Definition: Decl.cpp:2651
const Type * getTypePtr() const
Definition: Type.h:5016
llvm::Value * EvaluateExprAsBool(const Expr *E)
Definition: CGExpr.cpp:91
bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result)
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1717
llvm::Value * EmitVAListRef(const Expr *E)
void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty)
SanitizerSet SanOpts
Sanitizers enabled for this function.
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
const CodeGenOptions & getCodeGenOpts() const
static LValue MakeAddr(llvm::Value *address, QualType type, CharUnits alignment, ASTContext &Context, llvm::MDNode *TBAAInfo=nullptr)
Definition: CGValue.h:295
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
const LangOptions & getLangOpts() const
SourceLocation getBegin() const
void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB, llvm::BasicBlock::iterator InsertPt) const
This forwards to CodeGenFunction::InsertHelper.
MangleContext & getMangleContext()
Gets the mangle context.
Definition: CGCXXABI.h:85
void getCaptureFields(llvm::DenseMap< const VarDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
Definition: DeclCXX.cpp:1022
JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target)
llvm::Constant * EmitAnnotationLineNo(SourceLocation L)
Emit the annotation line number.
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:5086
const CGFunctionInfo * CurFnInfo
void EmitStartEHSpec(const Decl *D)
EmitStartEHSpec - Emit the start of the exception spec.
void FinishFunction(SourceLocation EndLoc=SourceLocation())
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
This is an IRBuilder insertion helper that forwards to CodeGenFunction::InsertHelper, which adds necessary metadata to instructions.
Definition: CGBuilder.h:24
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
llvm::Value * EmitFieldAnnotations(const FieldDecl *D, llvm::Value *V)
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
static const Type * getElementType(const Expr *BaseExpr)
bool isScalar() const
Definition: CGValue.h:47
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:116
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Definition: ASTMatchers.h:1639
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition: CGValue.h:54
llvm::Value * EmitAnnotationCall(llvm::Value *AnnotationFn, llvm::Value *AnnotatedVal, StringRef AnnotationStr, SourceLocation Location)
Emit an annotation call (intrinsic or builtin).
Decl * getNonClosureContext()
Definition: DeclBase.cpp:782
void buildThisParam(CodeGenFunction &CGF, FunctionArgList &Params)
Build a parameter variable suitable for 'this'.
Definition: CGCXXABI.cpp:152
llvm::Constant * EmitNullConstant(QualType T)
llvm::SmallVector< char, 256 > LifetimeExtendedCleanupStack
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1022
bool isInSanitizerBlacklist(llvm::Function *Fn, SourceLocation Loc) const
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2006
param_iterator param_end()
Definition: Decl.h:1948
JumpDest ReturnBlock
ReturnBlock - Unified return block.
void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S)
const T * getAs() const
Definition: Type.h:5555
QualType getCanonicalType() const
Definition: Type.h:5055
void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD)
Definition: CGClass.cpp:2461
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:52
llvm::AssertingVH< llvm::Instruction > AllocaInsertPt
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:5080
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
Definition: CGStmt.cpp:348
void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body)
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
void InsertHelper(llvm::Instruction *I) const
Function called by the CodeGenFunction when an instruction is created.
Definition: CGLoopInfo.cpp:119
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
void unprotectFromPeepholes(PeepholeProtection protection)
void ErrorUnsupported(const Stmt *S, const char *Type)
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:5096
BoundNodesTreeBuilder *const Builder
void EmitBranch(llvm::BasicBlock *Block)
Definition: CGStmt.cpp:368
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:470
llvm::Type * ConvertType(QualType T)
void EmitFunctionProlog(const CGFunctionInfo &FI, llvm::Function *Fn, const FunctionArgList &Args)
Definition: CGCall.cpp:1762
void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize)
Takes the old cleanup stack size and emits the cleanup blocks that have been added.
Definition: CGCleanup.cpp:388
LValue EmitLValue(const Expr *E)
Definition: CGExpr.cpp:831
bool AutoreleaseResult
In ARC, whether we should autorelease the return value.
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
Definition: CGExpr.cpp:1316
std::pair< llvm::Value *, QualType > getVLASize(const VariableArrayType *vla)
Defines the clang::TargetInfo interface.
llvm::MDNode * getTBAAInfo(QualType QTy)
unsigned getTargetAddressSpace(QualType T) const
Definition: ASTContext.h:2089
A reference to a declared variable, function, enum, etc. [C99 6.5.1p2].
Definition: Expr.h:899
void EmitDestructorBody(FunctionArgList &Args)
EmitDestructorBody - Emits the body of the current destructor.
Definition: CGClass.cpp:1390
QualType getElementType() const
Definition: Type.h:2434
void EmitEndEHSpec(const Decl *D)
EmitEndEHSpec - Emit the end of the exception spec.
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
Definition: CGExpr.cpp:2213
A trivial tuple used to represent a source range.
SourceLocation getLocation() const
Definition: DeclBase.h:372
llvm::BlockAddress * GetAddrOfLabel(const LabelDecl *L)
void EmitVarAnnotations(const VarDecl *D, llvm::Value *V)
Emit local annotations for the local variable V, declared by D.
SanitizerMetadata * getSanitizerMetadata()
bool isSignedIntegerType() const
Definition: Type.cpp:1683
void assignRegionCounters(const Decl *D, llvm::Function *Fn)
Definition: CodeGenPGO.cpp:660
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:5075
bool hasImplicitReturnZero() const
Definition: Decl.h:1816
static bool containsBreak(const Stmt *S)
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:877
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
bool isZeroInitializable(QualType T)
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
Attr - This represents one attribute.
Definition: Attr.h:44
Expr * IgnoreParens() LLVM_READONLY
Definition: Expr.cpp:2408
bool isPointerType() const
Definition: Type.h:5232
OverloadedOperatorKind getOverloadedOperator() const
Definition: Decl.cpp:2916