CodeGenFunction.cpp 65 KB

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