CodeGenFunction.cpp 46 KB

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