1 //===- BuildLibCalls.cpp - Utility builder for libcalls -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements some functions that will create standard C libcalls.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Transforms/Utils/BuildLibCalls.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/TargetLibraryInfo.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/IRBuilder.h"
21 #include "llvm/IR/Intrinsics.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Type.h"
25 
26 using namespace llvm;
27 
28 #define DEBUG_TYPE "build-libcalls"
29 
30 //- Infer Attributes ---------------------------------------------------------//
31 
32 STATISTIC(NumReadNone, "Number of functions inferred as readnone");
33 STATISTIC(NumReadOnly, "Number of functions inferred as readonly");
34 STATISTIC(NumArgMemOnly, "Number of functions inferred as argmemonly");
35 STATISTIC(NumNoUnwind, "Number of functions inferred as nounwind");
36 STATISTIC(NumNoCapture, "Number of arguments inferred as nocapture");
37 STATISTIC(NumReadOnlyArg, "Number of arguments inferred as readonly");
38 STATISTIC(NumNoAlias, "Number of function returns inferred as noalias");
39 STATISTIC(NumNonNull, "Number of function returns inferred as nonnull returns");
40 STATISTIC(NumReturnedArg, "Number of arguments inferred as returned");
41 
42 static bool setDoesNotAccessMemory(Function &F) {
43   if (F.doesNotAccessMemory())
44     return false;
45   F.setDoesNotAccessMemory();
46   ++NumReadNone;
47   return true;
48 }
49 
50 static bool setOnlyReadsMemory(Function &F) {
51   if (F.onlyReadsMemory())
52     return false;
53   F.setOnlyReadsMemory();
54   ++NumReadOnly;
55   return true;
56 }
57 
58 static bool setOnlyAccessesArgMemory(Function &F) {
59   if (F.onlyAccessesArgMemory())
60     return false;
61   F.setOnlyAccessesArgMemory();
62   ++NumArgMemOnly;
63   return true;
64 }
65 
66 static bool setDoesNotThrow(Function &F) {
67   if (F.doesNotThrow())
68     return false;
69   F.setDoesNotThrow();
70   ++NumNoUnwind;
71   return true;
72 }
73 
74 static bool setRetDoesNotAlias(Function &F) {
75   if (F.hasAttribute(AttributeList::ReturnIndex, Attribute::NoAlias))
76     return false;
77   F.addAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
78   ++NumNoAlias;
79   return true;
80 }
81 
82 static bool setDoesNotCapture(Function &F, unsigned ArgNo) {
83   if (F.hasParamAttribute(ArgNo, Attribute::NoCapture))
84     return false;
85   F.addParamAttr(ArgNo, Attribute::NoCapture);
86   ++NumNoCapture;
87   return true;
88 }
89 
90 static bool setOnlyReadsMemory(Function &F, unsigned ArgNo) {
91   if (F.hasParamAttribute(ArgNo, Attribute::ReadOnly))
92     return false;
93   F.addParamAttr(ArgNo, Attribute::ReadOnly);
94   ++NumReadOnlyArg;
95   return true;
96 }
97 
98 static bool setRetNonNull(Function &F) {
99   assert(F.getReturnType()->isPointerTy() &&
100          "nonnull applies only to pointers");
101   if (F.hasAttribute(AttributeList::ReturnIndex, Attribute::NonNull))
102     return false;
103   F.addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
104   ++NumNonNull;
105   return true;
106 }
107 
108 static bool setReturnedArg(Function &F, unsigned ArgNo) {
109   if (F.hasParamAttribute(ArgNo, Attribute::Returned))
110     return false;
111   F.addParamAttr(ArgNo, Attribute::Returned);
112   ++NumReturnedArg;
113   return true;
114 }
115 
116 static bool setNonLazyBind(Function &F) {
117   if (F.hasFnAttribute(Attribute::NonLazyBind))
118     return false;
119   F.addFnAttr(Attribute::NonLazyBind);
120   return true;
121 }
122 
123 bool llvm::inferLibFuncAttributes(Module *M, StringRef Name,
124                                   const TargetLibraryInfo &TLI) {
125   Function *F = M->getFunction(Name);
126   if (!F)
127     return false;
128   return inferLibFuncAttributes(*F, TLI);
129 }
130 
131 bool llvm::inferLibFuncAttributes(Function &F, const TargetLibraryInfo &TLI) {
132   LibFunc TheLibFunc;
133   if (!(TLI.getLibFunc(F, TheLibFunc) && TLI.has(TheLibFunc)))
134     return false;
135 
136   bool Changed = false;
137 
138   if (F.getParent() != nullptr && F.getParent()->getRtLibUseGOT())
139     Changed |= setNonLazyBind(F);
140 
141   switch (TheLibFunc) {
142   case LibFunc_strlen:
143   case LibFunc_wcslen:
144     Changed |= setOnlyReadsMemory(F);
145     Changed |= setDoesNotThrow(F);
146     Changed |= setOnlyAccessesArgMemory(F);
147     Changed |= setDoesNotCapture(F, 0);
148     return Changed;
149   case LibFunc_strchr:
150   case LibFunc_strrchr:
151     Changed |= setOnlyReadsMemory(F);
152     Changed |= setDoesNotThrow(F);
153     return Changed;
154   case LibFunc_strtol:
155   case LibFunc_strtod:
156   case LibFunc_strtof:
157   case LibFunc_strtoul:
158   case LibFunc_strtoll:
159   case LibFunc_strtold:
160   case LibFunc_strtoull:
161     Changed |= setDoesNotThrow(F);
162     Changed |= setDoesNotCapture(F, 1);
163     Changed |= setOnlyReadsMemory(F, 0);
164     return Changed;
165   case LibFunc_strcpy:
166   case LibFunc_strncpy:
167   case LibFunc_strcat:
168   case LibFunc_strncat:
169     Changed |= setReturnedArg(F, 0);
170     LLVM_FALLTHROUGH;
171   case LibFunc_stpcpy:
172   case LibFunc_stpncpy:
173     Changed |= setDoesNotThrow(F);
174     Changed |= setDoesNotCapture(F, 1);
175     Changed |= setOnlyReadsMemory(F, 1);
176     return Changed;
177   case LibFunc_strxfrm:
178     Changed |= setDoesNotThrow(F);
179     Changed |= setDoesNotCapture(F, 0);
180     Changed |= setDoesNotCapture(F, 1);
181     Changed |= setOnlyReadsMemory(F, 1);
182     return Changed;
183   case LibFunc_strcmp:      // 0,1
184   case LibFunc_strspn:      // 0,1
185   case LibFunc_strncmp:     // 0,1
186   case LibFunc_strcspn:     // 0,1
187   case LibFunc_strcoll:     // 0,1
188   case LibFunc_strcasecmp:  // 0,1
189   case LibFunc_strncasecmp: //
190     Changed |= setOnlyReadsMemory(F);
191     Changed |= setDoesNotThrow(F);
192     Changed |= setDoesNotCapture(F, 0);
193     Changed |= setDoesNotCapture(F, 1);
194     return Changed;
195   case LibFunc_strstr:
196   case LibFunc_strpbrk:
197     Changed |= setOnlyReadsMemory(F);
198     Changed |= setDoesNotThrow(F);
199     Changed |= setDoesNotCapture(F, 1);
200     return Changed;
201   case LibFunc_strtok:
202   case LibFunc_strtok_r:
203     Changed |= setDoesNotThrow(F);
204     Changed |= setDoesNotCapture(F, 1);
205     Changed |= setOnlyReadsMemory(F, 1);
206     return Changed;
207   case LibFunc_scanf:
208     Changed |= setDoesNotThrow(F);
209     Changed |= setDoesNotCapture(F, 0);
210     Changed |= setOnlyReadsMemory(F, 0);
211     return Changed;
212   case LibFunc_setbuf:
213   case LibFunc_setvbuf:
214     Changed |= setDoesNotThrow(F);
215     Changed |= setDoesNotCapture(F, 0);
216     return Changed;
217   case LibFunc_strdup:
218   case LibFunc_strndup:
219     Changed |= setDoesNotThrow(F);
220     Changed |= setRetDoesNotAlias(F);
221     Changed |= setDoesNotCapture(F, 0);
222     Changed |= setOnlyReadsMemory(F, 0);
223     return Changed;
224   case LibFunc_stat:
225   case LibFunc_statvfs:
226     Changed |= setDoesNotThrow(F);
227     Changed |= setDoesNotCapture(F, 0);
228     Changed |= setDoesNotCapture(F, 1);
229     Changed |= setOnlyReadsMemory(F, 0);
230     return Changed;
231   case LibFunc_sscanf:
232     Changed |= setDoesNotThrow(F);
233     Changed |= setDoesNotCapture(F, 0);
234     Changed |= setDoesNotCapture(F, 1);
235     Changed |= setOnlyReadsMemory(F, 0);
236     Changed |= setOnlyReadsMemory(F, 1);
237     return Changed;
238   case LibFunc_sprintf:
239     Changed |= setDoesNotThrow(F);
240     Changed |= setDoesNotCapture(F, 0);
241     Changed |= setDoesNotCapture(F, 1);
242     Changed |= setOnlyReadsMemory(F, 1);
243     return Changed;
244   case LibFunc_snprintf:
245     Changed |= setDoesNotThrow(F);
246     Changed |= setDoesNotCapture(F, 0);
247     Changed |= setDoesNotCapture(F, 2);
248     Changed |= setOnlyReadsMemory(F, 2);
249     return Changed;
250   case LibFunc_setitimer:
251     Changed |= setDoesNotThrow(F);
252     Changed |= setDoesNotCapture(F, 1);
253     Changed |= setDoesNotCapture(F, 2);
254     Changed |= setOnlyReadsMemory(F, 1);
255     return Changed;
256   case LibFunc_system:
257     // May throw; "system" is a valid pthread cancellation point.
258     Changed |= setDoesNotCapture(F, 0);
259     Changed |= setOnlyReadsMemory(F, 0);
260     return Changed;
261   case LibFunc_malloc:
262     Changed |= setDoesNotThrow(F);
263     Changed |= setRetDoesNotAlias(F);
264     return Changed;
265   case LibFunc_memcmp:
266     Changed |= setOnlyReadsMemory(F);
267     Changed |= setDoesNotThrow(F);
268     Changed |= setDoesNotCapture(F, 0);
269     Changed |= setDoesNotCapture(F, 1);
270     return Changed;
271   case LibFunc_memchr:
272   case LibFunc_memrchr:
273     Changed |= setOnlyReadsMemory(F);
274     Changed |= setDoesNotThrow(F);
275     return Changed;
276   case LibFunc_modf:
277   case LibFunc_modff:
278   case LibFunc_modfl:
279     Changed |= setDoesNotThrow(F);
280     Changed |= setDoesNotCapture(F, 1);
281     return Changed;
282   case LibFunc_memcpy:
283   case LibFunc_memmove:
284     Changed |= setReturnedArg(F, 0);
285     LLVM_FALLTHROUGH;
286   case LibFunc_mempcpy:
287   case LibFunc_memccpy:
288     Changed |= setDoesNotThrow(F);
289     Changed |= setDoesNotCapture(F, 1);
290     Changed |= setOnlyReadsMemory(F, 1);
291     return Changed;
292   case LibFunc_memcpy_chk:
293     Changed |= setDoesNotThrow(F);
294     return Changed;
295   case LibFunc_memalign:
296     Changed |= setRetDoesNotAlias(F);
297     return Changed;
298   case LibFunc_mkdir:
299     Changed |= setDoesNotThrow(F);
300     Changed |= setDoesNotCapture(F, 0);
301     Changed |= setOnlyReadsMemory(F, 0);
302     return Changed;
303   case LibFunc_mktime:
304     Changed |= setDoesNotThrow(F);
305     Changed |= setDoesNotCapture(F, 0);
306     return Changed;
307   case LibFunc_realloc:
308     Changed |= setDoesNotThrow(F);
309     Changed |= setRetDoesNotAlias(F);
310     Changed |= setDoesNotCapture(F, 0);
311     return Changed;
312   case LibFunc_read:
313     // May throw; "read" is a valid pthread cancellation point.
314     Changed |= setDoesNotCapture(F, 1);
315     return Changed;
316   case LibFunc_rewind:
317     Changed |= setDoesNotThrow(F);
318     Changed |= setDoesNotCapture(F, 0);
319     return Changed;
320   case LibFunc_rmdir:
321   case LibFunc_remove:
322   case LibFunc_realpath:
323     Changed |= setDoesNotThrow(F);
324     Changed |= setDoesNotCapture(F, 0);
325     Changed |= setOnlyReadsMemory(F, 0);
326     return Changed;
327   case LibFunc_rename:
328     Changed |= setDoesNotThrow(F);
329     Changed |= setDoesNotCapture(F, 0);
330     Changed |= setDoesNotCapture(F, 1);
331     Changed |= setOnlyReadsMemory(F, 0);
332     Changed |= setOnlyReadsMemory(F, 1);
333     return Changed;
334   case LibFunc_readlink:
335     Changed |= setDoesNotThrow(F);
336     Changed |= setDoesNotCapture(F, 0);
337     Changed |= setDoesNotCapture(F, 1);
338     Changed |= setOnlyReadsMemory(F, 0);
339     return Changed;
340   case LibFunc_write:
341     // May throw; "write" is a valid pthread cancellation point.
342     Changed |= setDoesNotCapture(F, 1);
343     Changed |= setOnlyReadsMemory(F, 1);
344     return Changed;
345   case LibFunc_bcopy:
346     Changed |= setDoesNotThrow(F);
347     Changed |= setDoesNotCapture(F, 0);
348     Changed |= setDoesNotCapture(F, 1);
349     Changed |= setOnlyReadsMemory(F, 0);
350     return Changed;
351   case LibFunc_bcmp:
352     Changed |= setDoesNotThrow(F);
353     Changed |= setOnlyReadsMemory(F);
354     Changed |= setDoesNotCapture(F, 0);
355     Changed |= setDoesNotCapture(F, 1);
356     return Changed;
357   case LibFunc_bzero:
358     Changed |= setDoesNotThrow(F);
359     Changed |= setDoesNotCapture(F, 0);
360     return Changed;
361   case LibFunc_calloc:
362     Changed |= setDoesNotThrow(F);
363     Changed |= setRetDoesNotAlias(F);
364     return Changed;
365   case LibFunc_chmod:
366   case LibFunc_chown:
367     Changed |= setDoesNotThrow(F);
368     Changed |= setDoesNotCapture(F, 0);
369     Changed |= setOnlyReadsMemory(F, 0);
370     return Changed;
371   case LibFunc_ctermid:
372   case LibFunc_clearerr:
373   case LibFunc_closedir:
374     Changed |= setDoesNotThrow(F);
375     Changed |= setDoesNotCapture(F, 0);
376     return Changed;
377   case LibFunc_atoi:
378   case LibFunc_atol:
379   case LibFunc_atof:
380   case LibFunc_atoll:
381     Changed |= setDoesNotThrow(F);
382     Changed |= setOnlyReadsMemory(F);
383     Changed |= setDoesNotCapture(F, 0);
384     return Changed;
385   case LibFunc_access:
386     Changed |= setDoesNotThrow(F);
387     Changed |= setDoesNotCapture(F, 0);
388     Changed |= setOnlyReadsMemory(F, 0);
389     return Changed;
390   case LibFunc_fopen:
391     Changed |= setDoesNotThrow(F);
392     Changed |= setRetDoesNotAlias(F);
393     Changed |= setDoesNotCapture(F, 0);
394     Changed |= setDoesNotCapture(F, 1);
395     Changed |= setOnlyReadsMemory(F, 0);
396     Changed |= setOnlyReadsMemory(F, 1);
397     return Changed;
398   case LibFunc_fdopen:
399     Changed |= setDoesNotThrow(F);
400     Changed |= setRetDoesNotAlias(F);
401     Changed |= setDoesNotCapture(F, 1);
402     Changed |= setOnlyReadsMemory(F, 1);
403     return Changed;
404   case LibFunc_feof:
405   case LibFunc_free:
406   case LibFunc_fseek:
407   case LibFunc_ftell:
408   case LibFunc_fgetc:
409   case LibFunc_fgetc_unlocked:
410   case LibFunc_fseeko:
411   case LibFunc_ftello:
412   case LibFunc_fileno:
413   case LibFunc_fflush:
414   case LibFunc_fclose:
415   case LibFunc_fsetpos:
416   case LibFunc_flockfile:
417   case LibFunc_funlockfile:
418   case LibFunc_ftrylockfile:
419     Changed |= setDoesNotThrow(F);
420     Changed |= setDoesNotCapture(F, 0);
421     return Changed;
422   case LibFunc_ferror:
423     Changed |= setDoesNotThrow(F);
424     Changed |= setDoesNotCapture(F, 0);
425     Changed |= setOnlyReadsMemory(F);
426     return Changed;
427   case LibFunc_fputc:
428   case LibFunc_fputc_unlocked:
429   case LibFunc_fstat:
430   case LibFunc_frexp:
431   case LibFunc_frexpf:
432   case LibFunc_frexpl:
433   case LibFunc_fstatvfs:
434     Changed |= setDoesNotThrow(F);
435     Changed |= setDoesNotCapture(F, 1);
436     return Changed;
437   case LibFunc_fgets:
438   case LibFunc_fgets_unlocked:
439     Changed |= setDoesNotThrow(F);
440     Changed |= setDoesNotCapture(F, 2);
441     return Changed;
442   case LibFunc_fread:
443   case LibFunc_fread_unlocked:
444     Changed |= setDoesNotThrow(F);
445     Changed |= setDoesNotCapture(F, 0);
446     Changed |= setDoesNotCapture(F, 3);
447     return Changed;
448   case LibFunc_fwrite:
449   case LibFunc_fwrite_unlocked:
450     Changed |= setDoesNotThrow(F);
451     Changed |= setDoesNotCapture(F, 0);
452     Changed |= setDoesNotCapture(F, 3);
453     // FIXME: readonly #1?
454     return Changed;
455   case LibFunc_fputs:
456   case LibFunc_fputs_unlocked:
457     Changed |= setDoesNotThrow(F);
458     Changed |= setDoesNotCapture(F, 0);
459     Changed |= setDoesNotCapture(F, 1);
460     Changed |= setOnlyReadsMemory(F, 0);
461     return Changed;
462   case LibFunc_fscanf:
463   case LibFunc_fprintf:
464     Changed |= setDoesNotThrow(F);
465     Changed |= setDoesNotCapture(F, 0);
466     Changed |= setDoesNotCapture(F, 1);
467     Changed |= setOnlyReadsMemory(F, 1);
468     return Changed;
469   case LibFunc_fgetpos:
470     Changed |= setDoesNotThrow(F);
471     Changed |= setDoesNotCapture(F, 0);
472     Changed |= setDoesNotCapture(F, 1);
473     return Changed;
474   case LibFunc_getc:
475   case LibFunc_getlogin_r:
476   case LibFunc_getc_unlocked:
477     Changed |= setDoesNotThrow(F);
478     Changed |= setDoesNotCapture(F, 0);
479     return Changed;
480   case LibFunc_getenv:
481     Changed |= setDoesNotThrow(F);
482     Changed |= setOnlyReadsMemory(F);
483     Changed |= setDoesNotCapture(F, 0);
484     return Changed;
485   case LibFunc_gets:
486   case LibFunc_getchar:
487   case LibFunc_getchar_unlocked:
488     Changed |= setDoesNotThrow(F);
489     return Changed;
490   case LibFunc_getitimer:
491     Changed |= setDoesNotThrow(F);
492     Changed |= setDoesNotCapture(F, 1);
493     return Changed;
494   case LibFunc_getpwnam:
495     Changed |= setDoesNotThrow(F);
496     Changed |= setDoesNotCapture(F, 0);
497     Changed |= setOnlyReadsMemory(F, 0);
498     return Changed;
499   case LibFunc_ungetc:
500     Changed |= setDoesNotThrow(F);
501     Changed |= setDoesNotCapture(F, 1);
502     return Changed;
503   case LibFunc_uname:
504     Changed |= setDoesNotThrow(F);
505     Changed |= setDoesNotCapture(F, 0);
506     return Changed;
507   case LibFunc_unlink:
508     Changed |= setDoesNotThrow(F);
509     Changed |= setDoesNotCapture(F, 0);
510     Changed |= setOnlyReadsMemory(F, 0);
511     return Changed;
512   case LibFunc_unsetenv:
513     Changed |= setDoesNotThrow(F);
514     Changed |= setDoesNotCapture(F, 0);
515     Changed |= setOnlyReadsMemory(F, 0);
516     return Changed;
517   case LibFunc_utime:
518   case LibFunc_utimes:
519     Changed |= setDoesNotThrow(F);
520     Changed |= setDoesNotCapture(F, 0);
521     Changed |= setDoesNotCapture(F, 1);
522     Changed |= setOnlyReadsMemory(F, 0);
523     Changed |= setOnlyReadsMemory(F, 1);
524     return Changed;
525   case LibFunc_putc:
526   case LibFunc_putc_unlocked:
527     Changed |= setDoesNotThrow(F);
528     Changed |= setDoesNotCapture(F, 1);
529     return Changed;
530   case LibFunc_puts:
531   case LibFunc_printf:
532   case LibFunc_perror:
533     Changed |= setDoesNotThrow(F);
534     Changed |= setDoesNotCapture(F, 0);
535     Changed |= setOnlyReadsMemory(F, 0);
536     return Changed;
537   case LibFunc_pread:
538     // May throw; "pread" is a valid pthread cancellation point.
539     Changed |= setDoesNotCapture(F, 1);
540     return Changed;
541   case LibFunc_pwrite:
542     // May throw; "pwrite" is a valid pthread cancellation point.
543     Changed |= setDoesNotCapture(F, 1);
544     Changed |= setOnlyReadsMemory(F, 1);
545     return Changed;
546   case LibFunc_putchar:
547   case LibFunc_putchar_unlocked:
548     Changed |= setDoesNotThrow(F);
549     return Changed;
550   case LibFunc_popen:
551     Changed |= setDoesNotThrow(F);
552     Changed |= setRetDoesNotAlias(F);
553     Changed |= setDoesNotCapture(F, 0);
554     Changed |= setDoesNotCapture(F, 1);
555     Changed |= setOnlyReadsMemory(F, 0);
556     Changed |= setOnlyReadsMemory(F, 1);
557     return Changed;
558   case LibFunc_pclose:
559     Changed |= setDoesNotThrow(F);
560     Changed |= setDoesNotCapture(F, 0);
561     return Changed;
562   case LibFunc_vscanf:
563     Changed |= setDoesNotThrow(F);
564     Changed |= setDoesNotCapture(F, 0);
565     Changed |= setOnlyReadsMemory(F, 0);
566     return Changed;
567   case LibFunc_vsscanf:
568     Changed |= setDoesNotThrow(F);
569     Changed |= setDoesNotCapture(F, 0);
570     Changed |= setDoesNotCapture(F, 1);
571     Changed |= setOnlyReadsMemory(F, 0);
572     Changed |= setOnlyReadsMemory(F, 1);
573     return Changed;
574   case LibFunc_vfscanf:
575     Changed |= setDoesNotThrow(F);
576     Changed |= setDoesNotCapture(F, 0);
577     Changed |= setDoesNotCapture(F, 1);
578     Changed |= setOnlyReadsMemory(F, 1);
579     return Changed;
580   case LibFunc_valloc:
581     Changed |= setDoesNotThrow(F);
582     Changed |= setRetDoesNotAlias(F);
583     return Changed;
584   case LibFunc_vprintf:
585     Changed |= setDoesNotThrow(F);
586     Changed |= setDoesNotCapture(F, 0);
587     Changed |= setOnlyReadsMemory(F, 0);
588     return Changed;
589   case LibFunc_vfprintf:
590   case LibFunc_vsprintf:
591     Changed |= setDoesNotThrow(F);
592     Changed |= setDoesNotCapture(F, 0);
593     Changed |= setDoesNotCapture(F, 1);
594     Changed |= setOnlyReadsMemory(F, 1);
595     return Changed;
596   case LibFunc_vsnprintf:
597     Changed |= setDoesNotThrow(F);
598     Changed |= setDoesNotCapture(F, 0);
599     Changed |= setDoesNotCapture(F, 2);
600     Changed |= setOnlyReadsMemory(F, 2);
601     return Changed;
602   case LibFunc_open:
603     // May throw; "open" is a valid pthread cancellation point.
604     Changed |= setDoesNotCapture(F, 0);
605     Changed |= setOnlyReadsMemory(F, 0);
606     return Changed;
607   case LibFunc_opendir:
608     Changed |= setDoesNotThrow(F);
609     Changed |= setRetDoesNotAlias(F);
610     Changed |= setDoesNotCapture(F, 0);
611     Changed |= setOnlyReadsMemory(F, 0);
612     return Changed;
613   case LibFunc_tmpfile:
614     Changed |= setDoesNotThrow(F);
615     Changed |= setRetDoesNotAlias(F);
616     return Changed;
617   case LibFunc_times:
618     Changed |= setDoesNotThrow(F);
619     Changed |= setDoesNotCapture(F, 0);
620     return Changed;
621   case LibFunc_htonl:
622   case LibFunc_htons:
623   case LibFunc_ntohl:
624   case LibFunc_ntohs:
625     Changed |= setDoesNotThrow(F);
626     Changed |= setDoesNotAccessMemory(F);
627     return Changed;
628   case LibFunc_lstat:
629     Changed |= setDoesNotThrow(F);
630     Changed |= setDoesNotCapture(F, 0);
631     Changed |= setDoesNotCapture(F, 1);
632     Changed |= setOnlyReadsMemory(F, 0);
633     return Changed;
634   case LibFunc_lchown:
635     Changed |= setDoesNotThrow(F);
636     Changed |= setDoesNotCapture(F, 0);
637     Changed |= setOnlyReadsMemory(F, 0);
638     return Changed;
639   case LibFunc_qsort:
640     // May throw; places call through function pointer.
641     Changed |= setDoesNotCapture(F, 3);
642     return Changed;
643   case LibFunc_dunder_strdup:
644   case LibFunc_dunder_strndup:
645     Changed |= setDoesNotThrow(F);
646     Changed |= setRetDoesNotAlias(F);
647     Changed |= setDoesNotCapture(F, 0);
648     Changed |= setOnlyReadsMemory(F, 0);
649     return Changed;
650   case LibFunc_dunder_strtok_r:
651     Changed |= setDoesNotThrow(F);
652     Changed |= setDoesNotCapture(F, 1);
653     Changed |= setOnlyReadsMemory(F, 1);
654     return Changed;
655   case LibFunc_under_IO_getc:
656     Changed |= setDoesNotThrow(F);
657     Changed |= setDoesNotCapture(F, 0);
658     return Changed;
659   case LibFunc_under_IO_putc:
660     Changed |= setDoesNotThrow(F);
661     Changed |= setDoesNotCapture(F, 1);
662     return Changed;
663   case LibFunc_dunder_isoc99_scanf:
664     Changed |= setDoesNotThrow(F);
665     Changed |= setDoesNotCapture(F, 0);
666     Changed |= setOnlyReadsMemory(F, 0);
667     return Changed;
668   case LibFunc_stat64:
669   case LibFunc_lstat64:
670   case LibFunc_statvfs64:
671     Changed |= setDoesNotThrow(F);
672     Changed |= setDoesNotCapture(F, 0);
673     Changed |= setDoesNotCapture(F, 1);
674     Changed |= setOnlyReadsMemory(F, 0);
675     return Changed;
676   case LibFunc_dunder_isoc99_sscanf:
677     Changed |= setDoesNotThrow(F);
678     Changed |= setDoesNotCapture(F, 0);
679     Changed |= setDoesNotCapture(F, 1);
680     Changed |= setOnlyReadsMemory(F, 0);
681     Changed |= setOnlyReadsMemory(F, 1);
682     return Changed;
683   case LibFunc_fopen64:
684     Changed |= setDoesNotThrow(F);
685     Changed |= setRetDoesNotAlias(F);
686     Changed |= setDoesNotCapture(F, 0);
687     Changed |= setDoesNotCapture(F, 1);
688     Changed |= setOnlyReadsMemory(F, 0);
689     Changed |= setOnlyReadsMemory(F, 1);
690     return Changed;
691   case LibFunc_fseeko64:
692   case LibFunc_ftello64:
693     Changed |= setDoesNotThrow(F);
694     Changed |= setDoesNotCapture(F, 0);
695     return Changed;
696   case LibFunc_tmpfile64:
697     Changed |= setDoesNotThrow(F);
698     Changed |= setRetDoesNotAlias(F);
699     return Changed;
700   case LibFunc_fstat64:
701   case LibFunc_fstatvfs64:
702     Changed |= setDoesNotThrow(F);
703     Changed |= setDoesNotCapture(F, 1);
704     return Changed;
705   case LibFunc_open64:
706     // May throw; "open" is a valid pthread cancellation point.
707     Changed |= setDoesNotCapture(F, 0);
708     Changed |= setOnlyReadsMemory(F, 0);
709     return Changed;
710   case LibFunc_gettimeofday:
711     // Currently some platforms have the restrict keyword on the arguments to
712     // gettimeofday. To be conservative, do not add noalias to gettimeofday's
713     // arguments.
714     Changed |= setDoesNotThrow(F);
715     Changed |= setDoesNotCapture(F, 0);
716     Changed |= setDoesNotCapture(F, 1);
717     return Changed;
718   case LibFunc_Znwj: // new(unsigned int)
719   case LibFunc_Znwm: // new(unsigned long)
720   case LibFunc_Znaj: // new[](unsigned int)
721   case LibFunc_Znam: // new[](unsigned long)
722   case LibFunc_msvc_new_int: // new(unsigned int)
723   case LibFunc_msvc_new_longlong: // new(unsigned long long)
724   case LibFunc_msvc_new_array_int: // new[](unsigned int)
725   case LibFunc_msvc_new_array_longlong: // new[](unsigned long long)
726     // Operator new always returns a nonnull noalias pointer
727     Changed |= setRetNonNull(F);
728     Changed |= setRetDoesNotAlias(F);
729     return Changed;
730   // TODO: add LibFunc entries for:
731   // case LibFunc_memset_pattern4:
732   // case LibFunc_memset_pattern8:
733   case LibFunc_memset_pattern16:
734     Changed |= setOnlyAccessesArgMemory(F);
735     Changed |= setDoesNotCapture(F, 0);
736     Changed |= setDoesNotCapture(F, 1);
737     Changed |= setOnlyReadsMemory(F, 1);
738     return Changed;
739   // int __nvvm_reflect(const char *)
740   case LibFunc_nvvm_reflect:
741     Changed |= setDoesNotAccessMemory(F);
742     Changed |= setDoesNotThrow(F);
743     return Changed;
744 
745   default:
746     // FIXME: It'd be really nice to cover all the library functions we're
747     // aware of here.
748     return false;
749   }
750 }
751 
752 bool llvm::hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
753                            LibFunc DoubleFn, LibFunc FloatFn,
754                            LibFunc LongDoubleFn) {
755   switch (Ty->getTypeID()) {
756   case Type::HalfTyID:
757     return false;
758   case Type::FloatTyID:
759     return TLI->has(FloatFn);
760   case Type::DoubleTyID:
761     return TLI->has(DoubleFn);
762   default:
763     return TLI->has(LongDoubleFn);
764   }
765 }
766 
767 StringRef llvm::getUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
768                                 LibFunc DoubleFn, LibFunc FloatFn,
769                                 LibFunc LongDoubleFn) {
770   assert(hasUnaryFloatFn(TLI, Ty, DoubleFn, FloatFn, LongDoubleFn) &&
771          "Cannot get name for unavailable function!");
772 
773   switch (Ty->getTypeID()) {
774   case Type::HalfTyID:
775     llvm_unreachable("No name for HalfTy!");
776   case Type::FloatTyID:
777     return TLI->getName(FloatFn);
778   case Type::DoubleTyID:
779     return TLI->getName(DoubleFn);
780   default:
781     return TLI->getName(LongDoubleFn);
782   }
783 }
784 
785 //- Emit LibCalls ------------------------------------------------------------//
786 
787 Value *llvm::castToCStr(Value *V, IRBuilder<> &B) {
788   unsigned AS = V->getType()->getPointerAddressSpace();
789   return B.CreateBitCast(V, B.getInt8PtrTy(AS), "cstr");
790 }
791 
792 static Value *emitLibCall(LibFunc TheLibFunc, Type *ReturnType,
793                           ArrayRef<Type *> ParamTypes,
794                           ArrayRef<Value *> Operands, IRBuilder<> &B,
795                           const TargetLibraryInfo *TLI,
796                           bool IsVaArgs = false) {
797   if (!TLI->has(TheLibFunc))
798     return nullptr;
799 
800   Module *M = B.GetInsertBlock()->getModule();
801   StringRef FuncName = TLI->getName(TheLibFunc);
802   FunctionType *FuncType = FunctionType::get(ReturnType, ParamTypes, IsVaArgs);
803   FunctionCallee Callee = M->getOrInsertFunction(FuncName, FuncType);
804   inferLibFuncAttributes(M, FuncName, *TLI);
805   CallInst *CI = B.CreateCall(Callee, Operands, FuncName);
806   if (const Function *F =
807           dyn_cast<Function>(Callee.getCallee()->stripPointerCasts()))
808     CI->setCallingConv(F->getCallingConv());
809   return CI;
810 }
811 
812 Value *llvm::emitStrLen(Value *Ptr, IRBuilder<> &B, const DataLayout &DL,
813                         const TargetLibraryInfo *TLI) {
814   LLVMContext &Context = B.GetInsertBlock()->getContext();
815   return emitLibCall(LibFunc_strlen, DL.getIntPtrType(Context),
816                      B.getInt8PtrTy(), castToCStr(Ptr, B), B, TLI);
817 }
818 
819 Value *llvm::emitStrChr(Value *Ptr, char C, IRBuilder<> &B,
820                         const TargetLibraryInfo *TLI) {
821   Type *I8Ptr = B.getInt8PtrTy();
822   Type *I32Ty = B.getInt32Ty();
823   return emitLibCall(LibFunc_strchr, I8Ptr, {I8Ptr, I32Ty},
824                      {castToCStr(Ptr, B), ConstantInt::get(I32Ty, C)}, B, TLI);
825 }
826 
827 Value *llvm::emitStrNCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B,
828                          const DataLayout &DL, const TargetLibraryInfo *TLI) {
829   LLVMContext &Context = B.GetInsertBlock()->getContext();
830   return emitLibCall(
831       LibFunc_strncmp, B.getInt32Ty(),
832       {B.getInt8PtrTy(), B.getInt8PtrTy(), DL.getIntPtrType(Context)},
833       {castToCStr(Ptr1, B), castToCStr(Ptr2, B), Len}, B, TLI);
834 }
835 
836 Value *llvm::emitStrCpy(Value *Dst, Value *Src, IRBuilder<> &B,
837                         const TargetLibraryInfo *TLI) {
838   Type *I8Ptr = B.getInt8PtrTy();
839   return emitLibCall(LibFunc_strcpy, I8Ptr, {I8Ptr, I8Ptr},
840                      {castToCStr(Dst, B), castToCStr(Src, B)}, B, TLI);
841 }
842 
843 Value *llvm::emitStpCpy(Value *Dst, Value *Src, IRBuilder<> &B,
844                         const TargetLibraryInfo *TLI) {
845   Type *I8Ptr = B.getInt8PtrTy();
846   return emitLibCall(LibFunc_stpcpy, I8Ptr, {I8Ptr, I8Ptr},
847                      {castToCStr(Dst, B), castToCStr(Src, B)}, B, TLI);
848 }
849 
850 Value *llvm::emitStrNCpy(Value *Dst, Value *Src, Value *Len, IRBuilder<> &B,
851                          const TargetLibraryInfo *TLI) {
852   Type *I8Ptr = B.getInt8PtrTy();
853   return emitLibCall(LibFunc_strncpy, I8Ptr, {I8Ptr, I8Ptr, Len->getType()},
854                      {castToCStr(Dst, B), castToCStr(Src, B), Len}, B, TLI);
855 }
856 
857 Value *llvm::emitStpNCpy(Value *Dst, Value *Src, Value *Len, IRBuilder<> &B,
858                          const TargetLibraryInfo *TLI) {
859   Type *I8Ptr = B.getInt8PtrTy();
860   return emitLibCall(LibFunc_stpncpy, I8Ptr, {I8Ptr, I8Ptr, Len->getType()},
861                      {castToCStr(Dst, B), castToCStr(Src, B), Len}, B, TLI);
862 }
863 
864 Value *llvm::emitMemCpyChk(Value *Dst, Value *Src, Value *Len, Value *ObjSize,
865                            IRBuilder<> &B, const DataLayout &DL,
866                            const TargetLibraryInfo *TLI) {
867   if (!TLI->has(LibFunc_memcpy_chk))
868     return nullptr;
869 
870   Module *M = B.GetInsertBlock()->getModule();
871   AttributeList AS;
872   AS = AttributeList::get(M->getContext(), AttributeList::FunctionIndex,
873                           Attribute::NoUnwind);
874   LLVMContext &Context = B.GetInsertBlock()->getContext();
875   FunctionCallee MemCpy = M->getOrInsertFunction(
876       "__memcpy_chk", AttributeList::get(M->getContext(), AS), B.getInt8PtrTy(),
877       B.getInt8PtrTy(), B.getInt8PtrTy(), DL.getIntPtrType(Context),
878       DL.getIntPtrType(Context));
879   Dst = castToCStr(Dst, B);
880   Src = castToCStr(Src, B);
881   CallInst *CI = B.CreateCall(MemCpy, {Dst, Src, Len, ObjSize});
882   if (const Function *F =
883           dyn_cast<Function>(MemCpy.getCallee()->stripPointerCasts()))
884     CI->setCallingConv(F->getCallingConv());
885   return CI;
886 }
887 
888 Value *llvm::emitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B,
889                         const DataLayout &DL, const TargetLibraryInfo *TLI) {
890   LLVMContext &Context = B.GetInsertBlock()->getContext();
891   return emitLibCall(
892       LibFunc_memchr, B.getInt8PtrTy(),
893       {B.getInt8PtrTy(), B.getInt32Ty(), DL.getIntPtrType(Context)},
894       {castToCStr(Ptr, B), Val, Len}, B, TLI);
895 }
896 
897 Value *llvm::emitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B,
898                         const DataLayout &DL, const TargetLibraryInfo *TLI) {
899   LLVMContext &Context = B.GetInsertBlock()->getContext();
900   return emitLibCall(
901       LibFunc_memcmp, B.getInt32Ty(),
902       {B.getInt8PtrTy(), B.getInt8PtrTy(), DL.getIntPtrType(Context)},
903       {castToCStr(Ptr1, B), castToCStr(Ptr2, B), Len}, B, TLI);
904 }
905 
906 Value *llvm::emitBCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B,
907                       const DataLayout &DL, const TargetLibraryInfo *TLI) {
908   LLVMContext &Context = B.GetInsertBlock()->getContext();
909   return emitLibCall(
910       LibFunc_bcmp, B.getInt32Ty(),
911       {B.getInt8PtrTy(), B.getInt8PtrTy(), DL.getIntPtrType(Context)},
912       {castToCStr(Ptr1, B), castToCStr(Ptr2, B), Len}, B, TLI);
913 }
914 
915 Value *llvm::emitMemCCpy(Value *Ptr1, Value *Ptr2, Value *Val, Value *Len,
916                          IRBuilder<> &B, const TargetLibraryInfo *TLI) {
917   return emitLibCall(
918       LibFunc_memccpy, B.getInt8PtrTy(),
919       {B.getInt8PtrTy(), B.getInt8PtrTy(), B.getInt32Ty(), Len->getType()},
920       {Ptr1, Ptr2, Val, Len}, B, TLI);
921 }
922 
923 Value *llvm::emitSNPrintf(Value *Dest, Value *Size, Value *Fmt,
924                           ArrayRef<Value *> VariadicArgs, IRBuilder<> &B,
925                           const TargetLibraryInfo *TLI) {
926   SmallVector<Value *, 8> Args{castToCStr(Dest, B), Size, castToCStr(Fmt, B)};
927   Args.insert(Args.end(), VariadicArgs.begin(), VariadicArgs.end());
928   return emitLibCall(LibFunc_snprintf, B.getInt32Ty(),
929                      {B.getInt8PtrTy(), Size->getType(), B.getInt8PtrTy()},
930                      Args, B, TLI, /*IsVaArgs=*/true);
931 }
932 
933 Value *llvm::emitSPrintf(Value *Dest, Value *Fmt,
934                          ArrayRef<Value *> VariadicArgs, IRBuilder<> &B,
935                          const TargetLibraryInfo *TLI) {
936   SmallVector<Value *, 8> Args{castToCStr(Dest, B), castToCStr(Fmt, B)};
937   Args.insert(Args.end(), VariadicArgs.begin(), VariadicArgs.end());
938   return emitLibCall(LibFunc_sprintf, B.getInt32Ty(),
939                      {B.getInt8PtrTy(), B.getInt8PtrTy()}, Args, B, TLI,
940                      /*IsVaArgs=*/true);
941 }
942 
943 Value *llvm::emitStrCat(Value *Dest, Value *Src, IRBuilder<> &B,
944                         const TargetLibraryInfo *TLI) {
945   return emitLibCall(LibFunc_strcat, B.getInt8PtrTy(),
946                      {B.getInt8PtrTy(), B.getInt8PtrTy()},
947                      {castToCStr(Dest, B), castToCStr(Src, B)}, B, TLI);
948 }
949 
950 Value *llvm::emitStrLCpy(Value *Dest, Value *Src, Value *Size, IRBuilder<> &B,
951                          const TargetLibraryInfo *TLI) {
952   return emitLibCall(LibFunc_strlcpy, Size->getType(),
953                      {B.getInt8PtrTy(), B.getInt8PtrTy(), Size->getType()},
954                      {castToCStr(Dest, B), castToCStr(Src, B), Size}, B, TLI);
955 }
956 
957 Value *llvm::emitStrLCat(Value *Dest, Value *Src, Value *Size, IRBuilder<> &B,
958                          const TargetLibraryInfo *TLI) {
959   return emitLibCall(LibFunc_strlcat, Size->getType(),
960                      {B.getInt8PtrTy(), B.getInt8PtrTy(), Size->getType()},
961                      {castToCStr(Dest, B), castToCStr(Src, B), Size}, B, TLI);
962 }
963 
964 Value *llvm::emitStrNCat(Value *Dest, Value *Src, Value *Size, IRBuilder<> &B,
965                          const TargetLibraryInfo *TLI) {
966   return emitLibCall(LibFunc_strncat, B.getInt8PtrTy(),
967                      {B.getInt8PtrTy(), B.getInt8PtrTy(), Size->getType()},
968                      {castToCStr(Dest, B), castToCStr(Src, B), Size}, B, TLI);
969 }
970 
971 Value *llvm::emitVSNPrintf(Value *Dest, Value *Size, Value *Fmt, Value *VAList,
972                            IRBuilder<> &B, const TargetLibraryInfo *TLI) {
973   return emitLibCall(
974       LibFunc_vsnprintf, B.getInt32Ty(),
975       {B.getInt8PtrTy(), Size->getType(), B.getInt8PtrTy(), VAList->getType()},
976       {castToCStr(Dest, B), Size, castToCStr(Fmt, B), VAList}, B, TLI);
977 }
978 
979 Value *llvm::emitVSPrintf(Value *Dest, Value *Fmt, Value *VAList,
980                           IRBuilder<> &B, const TargetLibraryInfo *TLI) {
981   return emitLibCall(LibFunc_vsprintf, B.getInt32Ty(),
982                      {B.getInt8PtrTy(), B.getInt8PtrTy(), VAList->getType()},
983                      {castToCStr(Dest, B), castToCStr(Fmt, B), VAList}, B, TLI);
984 }
985 
986 /// Append a suffix to the function name according to the type of 'Op'.
987 static void appendTypeSuffix(Value *Op, StringRef &Name,
988                              SmallString<20> &NameBuffer) {
989   if (!Op->getType()->isDoubleTy()) {
990       NameBuffer += Name;
991 
992     if (Op->getType()->isFloatTy())
993       NameBuffer += 'f';
994     else
995       NameBuffer += 'l';
996 
997     Name = NameBuffer;
998   }
999 }
1000 
1001 static Value *emitUnaryFloatFnCallHelper(Value *Op, StringRef Name,
1002                                          IRBuilder<> &B,
1003                                          const AttributeList &Attrs) {
1004   assert((Name != "") && "Must specify Name to emitUnaryFloatFnCall");
1005 
1006   Module *M = B.GetInsertBlock()->getModule();
1007   FunctionCallee Callee =
1008       M->getOrInsertFunction(Name, Op->getType(), Op->getType());
1009   CallInst *CI = B.CreateCall(Callee, Op, Name);
1010 
1011   // The incoming attribute set may have come from a speculatable intrinsic, but
1012   // is being replaced with a library call which is not allowed to be
1013   // speculatable.
1014   CI->setAttributes(Attrs.removeAttribute(B.getContext(),
1015                                           AttributeList::FunctionIndex,
1016                                           Attribute::Speculatable));
1017   if (const Function *F =
1018           dyn_cast<Function>(Callee.getCallee()->stripPointerCasts()))
1019     CI->setCallingConv(F->getCallingConv());
1020 
1021   return CI;
1022 }
1023 
1024 Value *llvm::emitUnaryFloatFnCall(Value *Op, StringRef Name, IRBuilder<> &B,
1025                                   const AttributeList &Attrs) {
1026   SmallString<20> NameBuffer;
1027   appendTypeSuffix(Op, Name, NameBuffer);
1028 
1029   return emitUnaryFloatFnCallHelper(Op, Name, B, Attrs);
1030 }
1031 
1032 Value *llvm::emitUnaryFloatFnCall(Value *Op, const TargetLibraryInfo *TLI,
1033                                   LibFunc DoubleFn, LibFunc FloatFn,
1034                                   LibFunc LongDoubleFn, IRBuilder<> &B,
1035                                   const AttributeList &Attrs) {
1036   // Get the name of the function according to TLI.
1037   StringRef Name = getUnaryFloatFn(TLI, Op->getType(),
1038                                    DoubleFn, FloatFn, LongDoubleFn);
1039 
1040   return emitUnaryFloatFnCallHelper(Op, Name, B, Attrs);
1041 }
1042 
1043 Value *llvm::emitBinaryFloatFnCall(Value *Op1, Value *Op2, StringRef Name,
1044                                    IRBuilder<> &B, const AttributeList &Attrs) {
1045   assert((Name != "") && "Must specify Name to emitBinaryFloatFnCall");
1046 
1047   SmallString<20> NameBuffer;
1048   appendTypeSuffix(Op1, Name, NameBuffer);
1049 
1050   Module *M = B.GetInsertBlock()->getModule();
1051   FunctionCallee Callee = M->getOrInsertFunction(
1052       Name, Op1->getType(), Op1->getType(), Op2->getType());
1053   CallInst *CI = B.CreateCall(Callee, {Op1, Op2}, Name);
1054   CI->setAttributes(Attrs);
1055   if (const Function *F =
1056           dyn_cast<Function>(Callee.getCallee()->stripPointerCasts()))
1057     CI->setCallingConv(F->getCallingConv());
1058 
1059   return CI;
1060 }
1061 
1062 Value *llvm::emitPutChar(Value *Char, IRBuilder<> &B,
1063                          const TargetLibraryInfo *TLI) {
1064   if (!TLI->has(LibFunc_putchar))
1065     return nullptr;
1066 
1067   Module *M = B.GetInsertBlock()->getModule();
1068   StringRef PutCharName = TLI->getName(LibFunc_putchar);
1069   FunctionCallee PutChar =
1070       M->getOrInsertFunction(PutCharName, B.getInt32Ty(), B.getInt32Ty());
1071   inferLibFuncAttributes(M, PutCharName, *TLI);
1072   CallInst *CI = B.CreateCall(PutChar,
1073                               B.CreateIntCast(Char,
1074                               B.getInt32Ty(),
1075                               /*isSigned*/true,
1076                               "chari"),
1077                               PutCharName);
1078 
1079   if (const Function *F =
1080           dyn_cast<Function>(PutChar.getCallee()->stripPointerCasts()))
1081     CI->setCallingConv(F->getCallingConv());
1082   return CI;
1083 }
1084 
1085 Value *llvm::emitPutS(Value *Str, IRBuilder<> &B,
1086                       const TargetLibraryInfo *TLI) {
1087   if (!TLI->has(LibFunc_puts))
1088     return nullptr;
1089 
1090   Module *M = B.GetInsertBlock()->getModule();
1091   StringRef PutsName = TLI->getName(LibFunc_puts);
1092   FunctionCallee PutS =
1093       M->getOrInsertFunction(PutsName, B.getInt32Ty(), B.getInt8PtrTy());
1094   inferLibFuncAttributes(M, PutsName, *TLI);
1095   CallInst *CI = B.CreateCall(PutS, castToCStr(Str, B), PutsName);
1096   if (const Function *F =
1097           dyn_cast<Function>(PutS.getCallee()->stripPointerCasts()))
1098     CI->setCallingConv(F->getCallingConv());
1099   return CI;
1100 }
1101 
1102 Value *llvm::emitFPutC(Value *Char, Value *File, IRBuilder<> &B,
1103                        const TargetLibraryInfo *TLI) {
1104   if (!TLI->has(LibFunc_fputc))
1105     return nullptr;
1106 
1107   Module *M = B.GetInsertBlock()->getModule();
1108   StringRef FPutcName = TLI->getName(LibFunc_fputc);
1109   FunctionCallee F = M->getOrInsertFunction(FPutcName, B.getInt32Ty(),
1110                                             B.getInt32Ty(), File->getType());
1111   if (File->getType()->isPointerTy())
1112     inferLibFuncAttributes(M, FPutcName, *TLI);
1113   Char = B.CreateIntCast(Char, B.getInt32Ty(), /*isSigned*/true,
1114                          "chari");
1115   CallInst *CI = B.CreateCall(F, {Char, File}, FPutcName);
1116 
1117   if (const Function *Fn =
1118           dyn_cast<Function>(F.getCallee()->stripPointerCasts()))
1119     CI->setCallingConv(Fn->getCallingConv());
1120   return CI;
1121 }
1122 
1123 Value *llvm::emitFPutCUnlocked(Value *Char, Value *File, IRBuilder<> &B,
1124                                const TargetLibraryInfo *TLI) {
1125   if (!TLI->has(LibFunc_fputc_unlocked))
1126     return nullptr;
1127 
1128   Module *M = B.GetInsertBlock()->getModule();
1129   StringRef FPutcUnlockedName = TLI->getName(LibFunc_fputc_unlocked);
1130   FunctionCallee F = M->getOrInsertFunction(FPutcUnlockedName, B.getInt32Ty(),
1131                                             B.getInt32Ty(), File->getType());
1132   if (File->getType()->isPointerTy())
1133     inferLibFuncAttributes(M, FPutcUnlockedName, *TLI);
1134   Char = B.CreateIntCast(Char, B.getInt32Ty(), /*isSigned*/ true, "chari");
1135   CallInst *CI = B.CreateCall(F, {Char, File}, FPutcUnlockedName);
1136 
1137   if (const Function *Fn =
1138           dyn_cast<Function>(F.getCallee()->stripPointerCasts()))
1139     CI->setCallingConv(Fn->getCallingConv());
1140   return CI;
1141 }
1142 
1143 Value *llvm::emitFPutS(Value *Str, Value *File, IRBuilder<> &B,
1144                        const TargetLibraryInfo *TLI) {
1145   if (!TLI->has(LibFunc_fputs))
1146     return nullptr;
1147 
1148   Module *M = B.GetInsertBlock()->getModule();
1149   StringRef FPutsName = TLI->getName(LibFunc_fputs);
1150   FunctionCallee F = M->getOrInsertFunction(FPutsName, B.getInt32Ty(),
1151                                             B.getInt8PtrTy(), File->getType());
1152   if (File->getType()->isPointerTy())
1153     inferLibFuncAttributes(M, FPutsName, *TLI);
1154   CallInst *CI = B.CreateCall(F, {castToCStr(Str, B), File}, FPutsName);
1155 
1156   if (const Function *Fn =
1157           dyn_cast<Function>(F.getCallee()->stripPointerCasts()))
1158     CI->setCallingConv(Fn->getCallingConv());
1159   return CI;
1160 }
1161 
1162 Value *llvm::emitFPutSUnlocked(Value *Str, Value *File, IRBuilder<> &B,
1163                                const TargetLibraryInfo *TLI) {
1164   if (!TLI->has(LibFunc_fputs_unlocked))
1165     return nullptr;
1166 
1167   Module *M = B.GetInsertBlock()->getModule();
1168   StringRef FPutsUnlockedName = TLI->getName(LibFunc_fputs_unlocked);
1169   FunctionCallee F = M->getOrInsertFunction(FPutsUnlockedName, B.getInt32Ty(),
1170                                             B.getInt8PtrTy(), File->getType());
1171   if (File->getType()->isPointerTy())
1172     inferLibFuncAttributes(M, FPutsUnlockedName, *TLI);
1173   CallInst *CI = B.CreateCall(F, {castToCStr(Str, B), File}, FPutsUnlockedName);
1174 
1175   if (const Function *Fn =
1176           dyn_cast<Function>(F.getCallee()->stripPointerCasts()))
1177     CI->setCallingConv(Fn->getCallingConv());
1178   return CI;
1179 }
1180 
1181 Value *llvm::emitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B,
1182                         const DataLayout &DL, const TargetLibraryInfo *TLI) {
1183   if (!TLI->has(LibFunc_fwrite))
1184     return nullptr;
1185 
1186   Module *M = B.GetInsertBlock()->getModule();
1187   LLVMContext &Context = B.GetInsertBlock()->getContext();
1188   StringRef FWriteName = TLI->getName(LibFunc_fwrite);
1189   FunctionCallee F = M->getOrInsertFunction(
1190       FWriteName, DL.getIntPtrType(Context), B.getInt8PtrTy(),
1191       DL.getIntPtrType(Context), DL.getIntPtrType(Context), File->getType());
1192 
1193   if (File->getType()->isPointerTy())
1194     inferLibFuncAttributes(M, FWriteName, *TLI);
1195   CallInst *CI =
1196       B.CreateCall(F, {castToCStr(Ptr, B), Size,
1197                        ConstantInt::get(DL.getIntPtrType(Context), 1), File});
1198 
1199   if (const Function *Fn =
1200           dyn_cast<Function>(F.getCallee()->stripPointerCasts()))
1201     CI->setCallingConv(Fn->getCallingConv());
1202   return CI;
1203 }
1204 
1205 Value *llvm::emitMalloc(Value *Num, IRBuilder<> &B, const DataLayout &DL,
1206                         const TargetLibraryInfo *TLI) {
1207   if (!TLI->has(LibFunc_malloc))
1208     return nullptr;
1209 
1210   Module *M = B.GetInsertBlock()->getModule();
1211   StringRef MallocName = TLI->getName(LibFunc_malloc);
1212   LLVMContext &Context = B.GetInsertBlock()->getContext();
1213   FunctionCallee Malloc = M->getOrInsertFunction(MallocName, B.getInt8PtrTy(),
1214                                                  DL.getIntPtrType(Context));
1215   inferLibFuncAttributes(M, MallocName, *TLI);
1216   CallInst *CI = B.CreateCall(Malloc, Num, MallocName);
1217 
1218   if (const Function *F =
1219           dyn_cast<Function>(Malloc.getCallee()->stripPointerCasts()))
1220     CI->setCallingConv(F->getCallingConv());
1221 
1222   return CI;
1223 }
1224 
1225 Value *llvm::emitCalloc(Value *Num, Value *Size, const AttributeList &Attrs,
1226                         IRBuilder<> &B, const TargetLibraryInfo &TLI) {
1227   if (!TLI.has(LibFunc_calloc))
1228     return nullptr;
1229 
1230   Module *M = B.GetInsertBlock()->getModule();
1231   StringRef CallocName = TLI.getName(LibFunc_calloc);
1232   const DataLayout &DL = M->getDataLayout();
1233   IntegerType *PtrType = DL.getIntPtrType((B.GetInsertBlock()->getContext()));
1234   FunctionCallee Calloc = M->getOrInsertFunction(
1235       CallocName, Attrs, B.getInt8PtrTy(), PtrType, PtrType);
1236   inferLibFuncAttributes(M, CallocName, TLI);
1237   CallInst *CI = B.CreateCall(Calloc, {Num, Size}, CallocName);
1238 
1239   if (const auto *F =
1240           dyn_cast<Function>(Calloc.getCallee()->stripPointerCasts()))
1241     CI->setCallingConv(F->getCallingConv());
1242 
1243   return CI;
1244 }
1245 
1246 Value *llvm::emitFWriteUnlocked(Value *Ptr, Value *Size, Value *N, Value *File,
1247                                 IRBuilder<> &B, const DataLayout &DL,
1248                                 const TargetLibraryInfo *TLI) {
1249   if (!TLI->has(LibFunc_fwrite_unlocked))
1250     return nullptr;
1251 
1252   Module *M = B.GetInsertBlock()->getModule();
1253   LLVMContext &Context = B.GetInsertBlock()->getContext();
1254   StringRef FWriteUnlockedName = TLI->getName(LibFunc_fwrite_unlocked);
1255   FunctionCallee F = M->getOrInsertFunction(
1256       FWriteUnlockedName, DL.getIntPtrType(Context), B.getInt8PtrTy(),
1257       DL.getIntPtrType(Context), DL.getIntPtrType(Context), File->getType());
1258 
1259   if (File->getType()->isPointerTy())
1260     inferLibFuncAttributes(M, FWriteUnlockedName, *TLI);
1261   CallInst *CI = B.CreateCall(F, {castToCStr(Ptr, B), Size, N, File});
1262 
1263   if (const Function *Fn =
1264           dyn_cast<Function>(F.getCallee()->stripPointerCasts()))
1265     CI->setCallingConv(Fn->getCallingConv());
1266   return CI;
1267 }
1268 
1269 Value *llvm::emitFGetCUnlocked(Value *File, IRBuilder<> &B,
1270                                const TargetLibraryInfo *TLI) {
1271   if (!TLI->has(LibFunc_fgetc_unlocked))
1272     return nullptr;
1273 
1274   Module *M = B.GetInsertBlock()->getModule();
1275   StringRef FGetCUnlockedName = TLI->getName(LibFunc_fgetc_unlocked);
1276   FunctionCallee F = M->getOrInsertFunction(FGetCUnlockedName, B.getInt32Ty(),
1277                                             File->getType());
1278   if (File->getType()->isPointerTy())
1279     inferLibFuncAttributes(M, FGetCUnlockedName, *TLI);
1280   CallInst *CI = B.CreateCall(F, File, FGetCUnlockedName);
1281 
1282   if (const Function *Fn =
1283           dyn_cast<Function>(F.getCallee()->stripPointerCasts()))
1284     CI->setCallingConv(Fn->getCallingConv());
1285   return CI;
1286 }
1287 
1288 Value *llvm::emitFGetSUnlocked(Value *Str, Value *Size, Value *File,
1289                                IRBuilder<> &B, const TargetLibraryInfo *TLI) {
1290   if (!TLI->has(LibFunc_fgets_unlocked))
1291     return nullptr;
1292 
1293   Module *M = B.GetInsertBlock()->getModule();
1294   StringRef FGetSUnlockedName = TLI->getName(LibFunc_fgets_unlocked);
1295   FunctionCallee F =
1296       M->getOrInsertFunction(FGetSUnlockedName, B.getInt8PtrTy(),
1297                              B.getInt8PtrTy(), B.getInt32Ty(), File->getType());
1298   inferLibFuncAttributes(M, FGetSUnlockedName, *TLI);
1299   CallInst *CI =
1300       B.CreateCall(F, {castToCStr(Str, B), Size, File}, FGetSUnlockedName);
1301 
1302   if (const Function *Fn =
1303           dyn_cast<Function>(F.getCallee()->stripPointerCasts()))
1304     CI->setCallingConv(Fn->getCallingConv());
1305   return CI;
1306 }
1307 
1308 Value *llvm::emitFReadUnlocked(Value *Ptr, Value *Size, Value *N, Value *File,
1309                                IRBuilder<> &B, const DataLayout &DL,
1310                                const TargetLibraryInfo *TLI) {
1311   if (!TLI->has(LibFunc_fread_unlocked))
1312     return nullptr;
1313 
1314   Module *M = B.GetInsertBlock()->getModule();
1315   LLVMContext &Context = B.GetInsertBlock()->getContext();
1316   StringRef FReadUnlockedName = TLI->getName(LibFunc_fread_unlocked);
1317   FunctionCallee F = M->getOrInsertFunction(
1318       FReadUnlockedName, DL.getIntPtrType(Context), B.getInt8PtrTy(),
1319       DL.getIntPtrType(Context), DL.getIntPtrType(Context), File->getType());
1320 
1321   if (File->getType()->isPointerTy())
1322     inferLibFuncAttributes(M, FReadUnlockedName, *TLI);
1323   CallInst *CI = B.CreateCall(F, {castToCStr(Ptr, B), Size, N, File});
1324 
1325   if (const Function *Fn =
1326           dyn_cast<Function>(F.getCallee()->stripPointerCasts()))
1327     CI->setCallingConv(Fn->getCallingConv());
1328   return CI;
1329 }
1330