Halide 19.0.0
Halide compiler and libraries
Loading...
Searching...
No Matches
CodeGen_LLVM.h
Go to the documentation of this file.
1#ifndef HALIDE_CODEGEN_LLVM_H
2#define HALIDE_CODEGEN_LLVM_H
3
4/** \file
5 *
6 * Defines the base-class for all architecture-specific code
7 * generators that use llvm.
8 */
9
10namespace llvm {
11class Value;
12class Module;
13class Function;
14class FunctionType;
15class IRBuilderDefaultInserter;
16class ConstantFolder;
17template<typename, typename>
19class LLVMContext;
20class Type;
21class StructType;
22class Instruction;
23class CallInst;
24class ExecutionEngine;
25class AllocaInst;
26class Constant;
27class Triple;
28class MDNode;
29class NamedMDNode;
30class DataLayout;
31class BasicBlock;
32class GlobalVariable;
33} // namespace llvm
34
35#include <map>
36#include <memory>
37#include <optional>
38#include <string>
39#include <variant>
40#include <vector>
41
42#include "IRVisitor.h"
43#include "Module.h"
44#include "Scope.h"
45#include "Target.h"
46
47namespace Halide {
48
49struct ExternSignature;
50
51namespace Internal {
52
53/** A code generator abstract base class. Actual code generators
54 * (e.g. CodeGen_X86) inherit from this. This class is responsible
55 * for taking a Halide Stmt and producing llvm bitcode, machine
56 * code in an object file, or machine code accessible through a
57 * function pointer.
58 */
59class CodeGen_LLVM : public IRVisitor {
60public:
61 /** Create an instance of CodeGen_LLVM suitable for the target. */
62 static std::unique_ptr<CodeGen_LLVM> new_for_target(const Target &target, llvm::LLVMContext &context);
63
64 /** Takes a halide Module and compiles it to an llvm Module. */
65 virtual std::unique_ptr<llvm::Module> compile(const Module &module);
66
67 /** The target we're generating code for */
68 const Target &get_target() const {
69 return target;
70 }
71
72 /** Tell the code generator which LLVM context to use. */
73 void set_context(llvm::LLVMContext &context);
74
75 /** Initialize internal llvm state for the enabled targets. */
76 static void initialize_llvm();
77
78 static std::unique_ptr<llvm::Module> compile_trampolines(
79 const Target &target,
80 llvm::LLVMContext &context,
81 const std::string &suffix,
82 const std::vector<std::pair<std::string, ExternSignature>> &externs);
83
86 }
87
88protected:
90
91 /** Compile a specific halide declaration into the llvm Module. */
92 // @{
93 virtual void compile_func(const LoweredFunc &func, const std::string &simple_name, const std::string &extern_name);
94 virtual void compile_buffer(const Buffer<> &buffer);
95 // @}
96
97 /** Helper functions for compiling Halide functions to llvm
98 * functions. begin_func performs all the work necessary to begin
99 * generating code for a function with a given argument list with
100 * the IRBuilder. A call to begin_func should be a followed by a
101 * call to end_func with the same arguments, to generate the
102 * appropriate cleanup code. */
103 // @{
104 virtual void begin_func(LinkageType linkage, const std::string &simple_name,
105 const std::string &extern_name, const std::vector<LoweredArgument> &args);
106 virtual void end_func(const std::vector<LoweredArgument> &args);
107 // @}
108
109 /** What should be passed as -mcpu (warning: implies attrs!), -mattrs,
110 * and related for compilation. The architecture-specific code generator
111 * should define these.
112 *
113 * `mcpu_target()` - target this specific CPU, in the sense of the allowed
114 * ISA sets *and* the CPU-specific tuning/assembly instruction scheduling.
115 *
116 * `mcpu_tune()` - expect that we will be running on this specific CPU,
117 * so perform CPU-specific tuning/assembly instruction scheduling, *but*
118 * DON'T sacrifice the portability, support running on other CPUs, only
119 * make use of the ISAs that are enabled by `mcpu_target()`+`mattrs()`.
120 */
121 // @{
122 virtual std::string mcpu_target() const = 0;
123 virtual std::string mcpu_tune() const = 0;
124 virtual std::string mattrs() const = 0;
125 virtual std::string mabi() const;
126 virtual bool use_soft_float_abi() const = 0;
127 virtual bool use_pic() const;
128 // @}
129
130 /** Should indexing math be promoted to 64-bit on platforms with
131 * 64-bit pointers? */
132 virtual bool promote_indices() const {
133 return true;
134 }
135
136 /** What's the natural vector bit-width to use for loads, stores, etc. */
137 virtual int native_vector_bits() const = 0;
138
139 /** Used to decide whether to break a vector up into multiple smaller
140 * operations. This is the largest size the architecture supports. */
141 virtual int maximum_vector_bits() const {
142 return native_vector_bits();
143 }
144 /** For architectures that have vscale vectors, return the constant vscale to use.
145 * Default of 0 means do not use vscale vectors. Generally will depend on
146 * the target flags and vector_bits settings.
147 */
148 virtual int target_vscale() const {
149 return 0;
150 }
151
152 /** Return the type in which arithmetic should be done for the
153 * given storage type. */
154 virtual Type upgrade_type_for_arithmetic(const Type &) const;
155
156 /** Return the type that a given Halide type should be
157 * stored/loaded from memory as. */
158 virtual Type upgrade_type_for_storage(const Type &) const;
159
160 /** Return the type that a Halide type should be passed in and out
161 * of functions as. */
163
164 std::unique_ptr<llvm::Module> module;
165 llvm::Function *function = nullptr;
166 llvm::LLVMContext *context = nullptr;
167 std::unique_ptr<llvm::IRBuilder<llvm::ConstantFolder, llvm::IRBuilderDefaultInserter>> builder;
168 llvm::Value *value = nullptr;
169 llvm::MDNode *very_likely_branch = nullptr;
170 llvm::MDNode *default_fp_math_md = nullptr;
171 llvm::MDNode *strict_fp_math_md = nullptr;
172 std::vector<LoweredArgument> current_function_args;
173
174 /** The target we're generating code for */
176
177 /** Grab all the context specific internal state. */
178 virtual void init_context();
179 /** Initialize the CodeGen_LLVM internal state to compile a fresh
180 * module. This allows reuse of one CodeGen_LLVM object to compiled
181 * multiple related modules (e.g. multiple device kernels). */
182 virtual void init_module();
183
184 /** Run all of llvm's optimization passes on the module. */
186
187 /** Add an entry to the symbol table, hiding previous entries with
188 * the same name. Call this when new values come into scope. */
189 void sym_push(const std::string &name, llvm::Value *value);
190
191 /** Remove an entry for the symbol table, revealing any previous
192 * entries with the same name. Call this when values go out of
193 * scope. */
194 void sym_pop(const std::string &name);
195
196 /** Fetch an entry from the symbol table. If the symbol is not
197 * found, it either errors out (if the second arg is true), or
198 * returns nullptr. */
199 llvm::Value *sym_get(const std::string &name,
200 bool must_succeed = true) const;
201
202 /** Test if an item exists in the symbol table. */
203 bool sym_exists(const std::string &name) const;
204
205 /** Given a Halide ExternSignature, return the equivalent llvm::FunctionType. */
206 llvm::FunctionType *signature_to_type(const ExternSignature &signature);
207
208 /** Some useful llvm types */
209 // @{
210 llvm::Type *void_t = nullptr, *i1_t = nullptr, *i8_t = nullptr, *i16_t = nullptr, *i32_t = nullptr, *i64_t = nullptr, *f16_t = nullptr, *f32_t = nullptr, *f64_t = nullptr;
211 llvm::StructType *halide_buffer_t_type = nullptr,
214 *metadata_t_type = nullptr,
215 *argument_t_type = nullptr,
220
221 // @}
222
223 /** Some wildcard variables used for peephole optimizations in
224 * subclasses */
225 // @{
229
230 // Wildcards for scalars.
234 // @}
235
236 /** Emit code that evaluates an expression, and return the llvm
237 * representation of the result of the expression. */
238 llvm::Value *codegen(const Expr &);
239
240 /** Emit code that runs a statement. */
241 void codegen(const Stmt &);
242
243 /** Codegen a vector Expr by codegenning each lane and combining. */
244 void scalarize(const Expr &);
245
246 /** Some destructors should always be called. Others should only
247 * be called if the pipeline is exiting with an error code. */
251
252 /* Call this at the location of object creation to register how an
253 * object should be destroyed. This does three things:
254 * 1) Emits code here that puts the object in a unique
255 * null-initialized stack slot
256 * 2) Adds an instruction to the destructor block that calls the
257 * destructor on that stack slot if it's not null.
258 * 3) Returns that stack slot, so you can neuter the destructor
259 * (by storing null to the stack slot) or destroy the object early
260 * (by calling trigger_destructor).
261 */
262 llvm::Value *register_destructor(llvm::Function *destructor_fn, llvm::Value *obj, DestructorType when);
263
264 /** Call a destructor early. Pass in the value returned by register destructor. */
265 void trigger_destructor(llvm::Function *destructor_fn, llvm::Value *stack_slot);
266
267 /** Retrieves the block containing the error handling
268 * code. Creates it if it doesn't already exist for this
269 * function. */
270 llvm::BasicBlock *get_destructor_block();
271
272 /** Codegen an assertion. If false, returns the error code (if not
273 * null), or evaluates and returns the message, which must be an
274 * Int(32) expression. */
275 // @{
276 void create_assertion(llvm::Value *condition, const Expr &message, llvm::Value *error_code = nullptr);
277 // @}
278
279 /** Codegen a block of asserts with pure conditions */
280 void codegen_asserts(const std::vector<const AssertStmt *> &asserts);
281
282 /** Return the the pipeline with the given error code. Will run
283 * the destructor block. */
285
286 /** Put a string constant in the module as a global variable and return a pointer to it. */
287 llvm::Constant *create_string_constant(const std::string &str);
288
289 /** Put a binary blob in the module as a global variable and return a pointer to it. */
290 llvm::Constant *create_binary_blob(const std::vector<char> &data, const std::string &name, bool constant = true);
291
292 /** Widen an llvm scalar into an llvm vector with the given number of lanes. */
293 llvm::Value *create_broadcast(llvm::Value *, int lanes);
294
295 /** Generate a pointer into a named buffer at a given index, of a
296 * given type. The index counts according to the scalar type of
297 * the type passed in. */
298 // @{
299 llvm::Value *codegen_buffer_pointer(const std::string &buffer, Type type, llvm::Value *index);
300 llvm::Value *codegen_buffer_pointer(const std::string &buffer, Type type, Expr index);
301 llvm::Value *codegen_buffer_pointer(llvm::Value *base_address, Type type, Expr index);
302 llvm::Value *codegen_buffer_pointer(llvm::Value *base_address, Type type, llvm::Value *index);
303 // @}
304
305 /** Return type string for LLVM type using LLVM IR intrinsic type mangling.
306 * E.g. ".i32 or ".f32" for scalars, ".p0" for pointers,
307 * ".nxv4i32" for a scalable vector of four 32-bit integers,
308 * or ".v4f32" for a fixed vector of four 32-bit floats.
309 * The dot is included in the result.
310 */
311 std::string mangle_llvm_type(llvm::Type *type);
312
313 /** Turn a Halide Type into an llvm::Value representing a constant halide_type_t */
314 llvm::Value *make_halide_type_t(const Type &);
315
316 /** Mark a load or store with type-based-alias-analysis metadata
317 * so that llvm knows it can reorder loads and stores across
318 * different buffers */
319 void add_tbaa_metadata(llvm::Instruction *inst, std::string buffer, const Expr &index);
320
321 /** Get a unique name for the actual block of memory that an
322 * allocate node uses. Used so that alias analysis understands
323 * when multiple Allocate nodes shared the same memory. */
324 virtual std::string get_allocation_name(const std::string &n) {
325 return n;
326 }
327
328 /** Add the appropriate function attribute to tell LLVM that the function
329 * doesn't access memory. */
330 void function_does_not_access_memory(llvm::Function *fn);
331
332 using IRVisitor::visit;
333
334 /** Generate code for various IR nodes. These can be overridden by
335 * architecture-specific code to perform peephole
336 * optimizations. The result of each is stored in \ref value */
337 // @{
338 void visit(const IntImm *) override;
339 void visit(const UIntImm *) override;
340 void visit(const FloatImm *) override;
341 void visit(const StringImm *) override;
342 void visit(const Cast *) override;
343 void visit(const Reinterpret *) override;
344 void visit(const Variable *) override;
345 void visit(const Add *) override;
346 void visit(const Sub *) override;
347 void visit(const Mul *) override;
348 void visit(const Div *) override;
349 void visit(const Mod *) override;
350 void visit(const Min *) override;
351 void visit(const Max *) override;
352 void visit(const EQ *) override;
353 void visit(const NE *) override;
354 void visit(const LT *) override;
355 void visit(const LE *) override;
356 void visit(const GT *) override;
357 void visit(const GE *) override;
358 void visit(const And *) override;
359 void visit(const Or *) override;
360 void visit(const Not *) override;
361 void visit(const Select *) override;
362 void visit(const Load *) override;
363 void visit(const Ramp *) override;
364 void visit(const Broadcast *) override;
365 void visit(const Call *) override;
366 void visit(const Let *) override;
367 void visit(const LetStmt *) override;
368 void visit(const AssertStmt *) override;
369 void visit(const ProducerConsumer *) override;
370 void visit(const For *) override;
371 void visit(const Store *) override;
372 void visit(const Block *) override;
373 void visit(const IfThenElse *) override;
374 void visit(const Evaluate *) override;
375 void visit(const Shuffle *) override;
376 void visit(const VectorReduce *) override;
377 void visit(const Prefetch *) override;
378 void visit(const Atomic *) override;
379 // @}
380
381 /** Generate code for an allocate node. It has no default
382 * implementation - it must be handled in an architecture-specific
383 * way. */
384 void visit(const Allocate *) override = 0;
385
386 /** Generate code for a free node. It has no default
387 * implementation and must be handled in an architecture-specific
388 * way. */
389 void visit(const Free *) override = 0;
390
391 /** These IR nodes should have been removed during
392 * lowering. CodeGen_LLVM will error out if they are present */
393 // @{
394 void visit(const Provide *) override;
395 void visit(const Realize *) override;
396 // @}
397
398 /** Get the llvm type equivalent to the given halide type in the
399 * current context. */
400 virtual llvm::Type *llvm_type_of(const Type &) const;
401
402 /** Get the llvm type equivalent to a given halide type. If
403 * effective_vscale is nonzero and the type is a vector type with lanes
404 * a multiple of effective_vscale, a scalable vector type is generated
405 * with total lanes divided by effective_vscale. That is a scalable
406 * vector intended to be used with a fixed vscale of effective_vscale.
407 */
408 llvm::Type *llvm_type_of(llvm::LLVMContext *context, Halide::Type t,
409 int effective_vscale) const;
410
411 /** Perform an alloca at the function entrypoint. Will be cleaned
412 * on function exit. */
413 llvm::Value *create_alloca_at_entry(llvm::Type *type, int n,
414 bool zero_initialize = false,
415 const std::string &name = "");
416
417 /** A (very) conservative guess at the size of all alloca() storage requested
418 * (including alignment padding). It's currently meant only to be used as
419 * a very coarse way to ensure there is enough stack space when testing
420 * on the WebAssembly backend.
421 *
422 * It is *not* meant to be a useful proxy for "stack space needed", for a
423 * number of reasons:
424 * - allocas with non-overlapping lifetimes will share space
425 * - on some backends, LLVM may promote register-sized allocas into registers
426 * - while this accounts for alloca() calls we know about, it doesn't attempt
427 * to account for stack spills, function call overhead, etc.
428 */
430
431 /** The user_context argument. May be a constant null if the
432 * function is being compiled without a user context. */
433 llvm::Value *get_user_context() const;
434
435 /** Implementation of the intrinsic call to
436 * interleave_vectors. This implementation allows for interleaving
437 * an arbitrary number of vectors.*/
438 virtual llvm::Value *interleave_vectors(const std::vector<llvm::Value *> &);
439
440 /** Description of an intrinsic function overload. Overloads are resolved
441 * using both argument and return types. The scalar types of the arguments
442 * and return type must match exactly for an overload resolution to succeed. */
443 struct Intrinsic {
445 std::vector<Type> arg_types;
446 llvm::Function *impl;
447
448 Intrinsic(Type result_type, std::vector<Type> arg_types, llvm::Function *impl)
450 }
451 };
452 /** Mapping of intrinsic functions to the various overloads implementing it. */
453 std::map<std::string, std::vector<Intrinsic>> intrinsics;
454
455 /** Get an LLVM intrinsic declaration. If it doesn't exist, it will be created. */
456 llvm::Function *get_llvm_intrin(const Type &ret_type, const std::string &name, const std::vector<Type> &arg_types, bool scalars_are_vectors = false);
457 llvm::Function *get_llvm_intrin(llvm::Type *ret_type, const std::string &name, const std::vector<llvm::Type *> &arg_types);
458 /** Declare an intrinsic function that participates in overload resolution. */
459 llvm::Function *declare_intrin_overload(const std::string &name, const Type &ret_type, const std::string &impl_name, std::vector<Type> arg_types, bool scalars_are_vectors = false);
460 void declare_intrin_overload(const std::string &name, const Type &ret_type, llvm::Function *impl, std::vector<Type> arg_types);
461 /** Call an overloaded intrinsic function. Returns nullptr if no suitable overload is found. */
462 llvm::Value *call_overloaded_intrin(const Type &result_type, const std::string &name, const std::vector<Expr> &args);
463
464 /** Generate a call to a vector intrinsic or runtime inlined
465 * function. The arguments are sliced up into vectors of the width
466 * given by 'intrin_lanes', the intrinsic is called on each
467 * piece, then the results (if any) are concatenated back together
468 * into the original type 't'. For the version that takes an
469 * llvm::Type *, the type may be void, so the vector width of the
470 * arguments must be specified explicitly as
471 * 'called_lanes'. */
472 // @{
473 llvm::Value *call_intrin(const Type &t, int intrin_lanes,
474 const std::string &name, std::vector<Expr>);
475 llvm::Value *call_intrin(const Type &t, int intrin_lanes,
476 llvm::Function *intrin, std::vector<Expr>);
477 llvm::Value *call_intrin(const llvm::Type *t, int intrin_lanes,
478 const std::string &name, std::vector<llvm::Value *>,
479 bool scalable_vector_result = false, bool is_reduction = false);
480 llvm::Value *call_intrin(const llvm::Type *t, int intrin_lanes,
481 llvm::Function *intrin, std::vector<llvm::Value *>,
482 bool is_reduction = false);
483 // @}
484
485 /** Take a slice of lanes out of an llvm vector. Pads with undefs
486 * if you ask for more lanes than the vector has. */
487 virtual llvm::Value *slice_vector(llvm::Value *vec, int start, int extent);
488
489 /** Concatenate a bunch of llvm vectors. Must be of the same type. */
490 virtual llvm::Value *concat_vectors(const std::vector<llvm::Value *> &);
491
492 /** Create an LLVM shuffle vectors instruction. Takes a combination of
493 * fixed or scalable vectors as input, so long as the effective lengths match,
494 * but always returns a fixed vector. */
495 virtual llvm::Value *shuffle_vectors(llvm::Value *a, llvm::Value *b,
496 const std::vector<int> &indices);
497 /** Shorthand for shuffling a single vector. */
498 llvm::Value *shuffle_vectors(llvm::Value *v, const std::vector<int> &indices);
499
500 /** Go looking for a vector version of a runtime function. Will
501 * return the best match. Matches in the following order:
502 *
503 * 1) The requested vector width.
504 *
505 * 2) The width which is the smallest power of two
506 * greater than or equal to the vector width.
507 *
508 * 3) All the factors of 2) greater than one, in decreasing order.
509 *
510 * 4) The smallest power of two not yet tried.
511 *
512 * So for a 5-wide vector, it tries: 5, 8, 4, 2, 16.
513 *
514 * If there's no match, returns (nullptr, 0).
515 */
516 std::pair<llvm::Function *, int> find_vector_runtime_function(const std::string &name, int lanes);
517
518 virtual bool supports_atomic_add(const Type &t) const;
519
520 /** Compile a horizontal reduction that starts with an explicit
521 * initial value. There are lots of complex ways to peephole
522 * optimize this pattern, especially with the proliferation of
523 * dot-product instructions, and they can usefully share logic
524 * across backends. */
525 virtual void codegen_vector_reduce(const VectorReduce *op, const Expr &init);
526
527 /** Are we inside an atomic node that uses mutex locks?
528 This is used for detecting deadlocks from nested atomics & illegal vectorization. */
530
531 /** Emit atomic store instructions? */
532 bool emit_atomic_stores = false;
533
534 /** Can we call this operation with float16 type?
535 This is used to avoid "emulated" equivalent code-gen in case target has FP16 feature **/
536 virtual bool supports_call_as_float16(const Call *op) const;
537
538 /** call_intrin does far too much to be useful and generally breaks things
539 * when one has carefully set things up for a specific architecture. This
540 * just does the bare minimum. call_intrin should be refactored and could
541 * call this, possibly with renaming of the methods. */
542 llvm::Value *simple_call_intrin(const std::string &intrin,
543 const std::vector<llvm::Value *> &args,
544 llvm::Type *result_type);
545
546 /** Ensure that a vector value is either fixed or vscale depending to match desired_type.
547 */
548 llvm::Value *normalize_fixed_scalable_vector_type(llvm::Type *desired_type, llvm::Value *result);
549
550 /** Convert between two LLVM vectors of potentially different scalable/fixed and size.
551 * Used to handle converting to/from fixed vectors that are smaller than the minimum
552 * size scalable vector. */
553 llvm::Value *convert_fixed_or_scalable_vector_type(llvm::Value *arg,
554 llvm::Type *desired_type);
555
556 /** Convert an LLVM fixed vector value to the corresponding vscale vector value. */
557 llvm::Value *fixed_to_scalable_vector_type(llvm::Value *fixed);
558
559 /** Convert an LLVM vscale vector value to the corresponding fixed vector value. */
560 llvm::Value *scalable_to_fixed_vector_type(llvm::Value *scalable);
561
562 /** Get number of vector elements, taking into account scalable vectors. Returns 1 for scalars. */
563 int get_vector_num_elements(const llvm::Type *t);
564
565 /** Interface to abstract vector code generation as LLVM is now
566 * providing multiple options to express even simple vector
567 * operations. Specifically traditional fixed length vectors, vscale
568 * based variable length vectors, and the vector predicate based approach
569 * where an explict length is passed with each instruction.
570 */
571 // @{
573 None, /// Use default for current target.
574 Fixed, /// Force use of fixed size vectors.
575 VScale, /// For use of scalable vectors.
576 };
577 llvm::Type *get_vector_type(llvm::Type *, int n,
578 VectorTypeConstraint type_constraint = VectorTypeConstraint::None) const;
579 // @}
580
581 llvm::Constant *get_splat(int lanes, llvm::Constant *value,
582 VectorTypeConstraint type_constraint = VectorTypeConstraint::None) const;
583
584 /** Make sure a value type has the same scalable/fixed vector type as a guide. */
585 // @{
586 llvm::Value *match_vector_type_scalable(llvm::Value *value, VectorTypeConstraint constraint);
587 llvm::Value *match_vector_type_scalable(llvm::Value *value, llvm::Type *guide);
588 llvm::Value *match_vector_type_scalable(llvm::Value *value, llvm::Value *guide);
589 // @}
590
591 /** Support for generating LLVM vector predication intrinsics
592 * ("@llvm.vp.*" and "@llvm.experimental.vp.*")
593 */
594 // @{
595 /** Struct to hold descriptor for an argument to a vector
596 * predicated intrinsic. This includes the value, whether the
597 * type of the argument should be mangled into the intrisic name
598 * and if so, where, and the alignment for pointer arguments. */
599 struct VPArg {
600 llvm::Value *value;
601 // If provided, put argument's type into the intrinsic name via LLVM IR type mangling.
602 std::optional<size_t> mangle_index;
604 VPArg(llvm::Value *value, std::optional<size_t> mangle_index = std::nullopt, int32_t alignment = 0)
606 }
607 };
608
609 /** Type indicating an intrinsic does not take a mask. */
610 struct NoMask {
611 };
612
613 /** Type indicating mask to use is all true -- all lanes enabled. */
615 };
616
617 /** Predication mask using the above two types for special cases
618 * and an llvm::Value for the general one. */
619 using MaskVariant = std::variant<NoMask, AllEnabledMask, llvm::Value *>;
620
621 /** Generate a vector predicated comparison intrinsic call if
622 * use_llvm_vp_intrinsics is true and result_type is a vector
623 * type. If generated, assigns result of vp intrinsic to value and
624 * returns true if it an instuction is generated, otherwise
625 * returns false. */
626 bool try_vector_predication_comparison(const std::string &name, const Type &result_type,
627 MaskVariant mask, llvm::Value *a, llvm::Value *b,
628 const char *cmp_op);
629
631 llvm::Type *type;
632 std::optional<size_t> mangle_index;
633 VPResultType(llvm::Type *type, std::optional<size_t> mangle_index = std::nullopt)
635 }
636 };
637
638 /** Generate an intrisic call if use_llvm_vp_intrinsics is true
639 * and length is greater than 1. If generated, assigns result
640 * of vp intrinsic to value and returns true if it an instuction
641 * is generated, otherwise returns false. */
642 bool try_vector_predication_intrinsic(const std::string &name, VPResultType result_type,
643 int32_t length, MaskVariant mask, std::vector<VPArg> args);
644
645 /** Controls use of vector predicated intrinsics for vector operations.
646 * Will be set by certain backends (e.g. RISC V) to control codegen. */
648 // @}
649
650 /** Generate a basic dense vector load, with an optional predicate and
651 * control over whether or not we should slice the load into native
652 * vectors. Used by CodeGen_ARM to help with vld2/3/4 emission. */
653 llvm::Value *codegen_dense_vector_load(const Load *load, llvm::Value *vpred = nullptr, bool slice_to_native = true);
654
655 /** Warning messages which we want to avoid displaying number of times */
656 enum class WarningKind {
658 };
659 std::map<WarningKind, std::string> onetime_warnings;
660
661private:
662 /** All the values in scope at the current code location during
663 * codegen. Use sym_push and sym_pop to access. */
664 Scope<llvm::Value *> symbol_table;
665
666 /** String constants already emitted to the module. Tracked to
667 * prevent emitting the same string many times. */
668 std::map<std::string, llvm::Constant *> string_constants;
669
670 /** A basic block to branch to on error that triggers all
671 * destructors. As destructors are registered, code gets added
672 * to this block. */
673 llvm::BasicBlock *destructor_block = nullptr;
674
675 /** Turn off all unsafe math flags in scopes while this is set. */
676 bool strict_float;
677
678 /** Use the LLVM large code model when this is set. */
679 bool llvm_large_code_model;
680
681 /** Cache the result of target_vscale from architecture specific implementation
682 * as this is used on every Halide to LLVM type conversion.
683 */
684 int effective_vscale = 0;
685
686 /** Assign a unique ID to each producer-consumer and for-loop node. The IDs
687 * are printed as comments in assembly and used to link visualizations with
688 * the generated assembly code within `StmtToViz`
689 */
690 int producer_consumer_id = 0;
691 int for_loop_id = 0;
692
693 /** Embed an instance of halide_filter_metadata_t in the code, using
694 * the given name (by convention, this should be ${FUNCTIONNAME}_metadata)
695 * as extern "C" linkage. Note that the return value is a function-returning-
696 * pointer-to-constant-data.
697 */
698 llvm::Function *embed_metadata_getter(const std::string &metadata_getter_name,
699 const std::string &function_name, const std::vector<LoweredArgument> &args,
700 const MetadataNameMap &metadata_name_map);
701
702 /** Embed a constant expression as a global variable. */
703 llvm::Constant *embed_constant_expr(Expr e, llvm::Type *t);
704 llvm::Constant *embed_constant_scalar_value_t(const Expr &e);
705
706 llvm::Function *add_argv_wrapper(llvm::Function *fn, const std::string &name,
707 bool result_in_argv, std::vector<bool> &arg_is_buffer);
708
709 llvm::Value *codegen_vector_load(const Type &type, const std::string &name, const Expr &base,
710 const Buffer<> &image, const Parameter &param, const ModulusRemainder &alignment,
711 llvm::Value *vpred = nullptr, bool slice_to_native = true, llvm::Value *stride = nullptr);
712
713 virtual void codegen_predicated_load(const Load *op);
714 virtual void codegen_predicated_store(const Store *op);
715
716 void codegen_atomic_rmw(const Store *op);
717
718 void init_codegen(const std::string &name, bool any_strict_float = false);
719 std::unique_ptr<llvm::Module> finish_codegen();
720
721 /** A helper routine for generating folded vector reductions. */
722 template<typename Op>
723 bool try_to_fold_vector_reduce(const Expr &a, Expr b);
724
725 /** Records the StructType for pointer values returned from
726 * make_struct intrinsic. Required for opaque pointer support.
727 * This map should never grow without bound as each entry
728 * represents a unique struct type created by a closure or similar.
729 */
730 std::map<llvm::Value *, llvm::Type *> struct_type_recovery;
731};
732
733} // namespace Internal
734
735/** Given a Halide module, generate an llvm::Module. */
736std::unique_ptr<llvm::Module> codegen_llvm(const Module &module,
737 llvm::LLVMContext &context);
738
739} // namespace Halide
740
741#endif
Defines the base class for things that recursively walk over the IR.
Defines Module, an IR container that fully describes a Halide program.
Defines the Scope class, which is used for keeping track of names in a scope while traversing IR.
Defines the structure that describes a Halide target.
A code generator abstract base class.
llvm::Constant * get_splat(int lanes, llvm::Constant *value, VectorTypeConstraint type_constraint=VectorTypeConstraint::None) const
void visit(const Let *) override
std::pair< llvm::Function *, int > find_vector_runtime_function(const std::string &name, int lanes)
Go looking for a vector version of a runtime function.
llvm::StructType * metadata_t_type
virtual void end_func(const std::vector< LoweredArgument > &args)
llvm::StructType * argument_t_type
llvm::Constant * create_binary_blob(const std::vector< char > &data, const std::string &name, bool constant=true)
Put a binary blob in the module as a global variable and return a pointer to it.
void visit(const Select *) override
virtual int maximum_vector_bits() const
Used to decide whether to break a vector up into multiple smaller operations.
void visit(const Or *) override
void visit(const AssertStmt *) override
bool emit_atomic_stores
Emit atomic store instructions?
void sym_pop(const std::string &name)
Remove an entry for the symbol table, revealing any previous entries with the same name.
virtual void init_context()
Grab all the context specific internal state.
virtual int target_vscale() const
For architectures that have vscale vectors, return the constant vscale to use.
llvm::StructType * device_interface_t_type
void visit(const Mul *) override
llvm::StructType * semaphore_t_type
virtual bool supports_atomic_add(const Type &t) const
virtual llvm::Type * llvm_type_of(const Type &) const
Get the llvm type equivalent to the given halide type in the current context.
std::vector< LoweredArgument > current_function_args
const Target & get_target() const
The target we're generating code for.
void return_with_error_code(llvm::Value *error_code)
Return the the pipeline with the given error code.
llvm::Value * call_intrin(const llvm::Type *t, int intrin_lanes, const std::string &name, std::vector< llvm::Value * >, bool scalable_vector_result=false, bool is_reduction=false)
virtual std::unique_ptr< llvm::Module > compile(const Module &module)
Takes a halide Module and compiles it to an llvm Module.
llvm::Value * codegen_buffer_pointer(const std::string &buffer, Type type, Expr index)
llvm::Function * get_llvm_intrin(llvm::Type *ret_type, const std::string &name, const std::vector< llvm::Type * > &arg_types)
virtual std::string mcpu_tune() const =0
bool try_vector_predication_intrinsic(const std::string &name, VPResultType result_type, int32_t length, MaskVariant mask, std::vector< VPArg > args)
Generate an intrisic call if use_llvm_vp_intrinsics is true and length is greater than 1.
void trigger_destructor(llvm::Function *destructor_fn, llvm::Value *stack_slot)
Call a destructor early.
void visit(const Reinterpret *) override
void visit(const Min *) override
void visit(const For *) override
llvm::Value * codegen_buffer_pointer(llvm::Value *base_address, Type type, llvm::Value *index)
void visit(const Not *) override
void visit(const Sub *) override
void sym_push(const std::string &name, llvm::Value *value)
Add an entry to the symbol table, hiding previous entries with the same name.
llvm::StructType * type_t_type
VectorTypeConstraint
Interface to abstract vector code generation as LLVM is now providing multiple options to express eve...
@ VScale
Force use of fixed size vectors.
DestructorType
Some destructors should always be called.
Halide::Target target
The target we're generating code for.
virtual void begin_func(LinkageType linkage, const std::string &simple_name, const std::string &extern_name, const std::vector< LoweredArgument > &args)
Helper functions for compiling Halide functions to llvm functions.
bool try_vector_predication_comparison(const std::string &name, const Type &result_type, MaskVariant mask, llvm::Value *a, llvm::Value *b, const char *cmp_op)
Generate a vector predicated comparison intrinsic call if use_llvm_vp_intrinsics is true and result_t...
llvm::StructType * scalar_value_t_type
std::unique_ptr< llvm::IRBuilder< llvm::ConstantFolder, llvm::IRBuilderDefaultInserter > > builder
bool use_llvm_vp_intrinsics
Controls use of vector predicated intrinsics for vector operations.
llvm::Value * create_broadcast(llvm::Value *, int lanes)
Widen an llvm scalar into an llvm vector with the given number of lanes.
std::unique_ptr< llvm::Module > module
virtual std::string mcpu_target() const =0
What should be passed as -mcpu (warning: implies attrs!), -mattrs, and related for compilation.
void visit(const Max *) override
void codegen(const Stmt &)
Emit code that runs a statement.
virtual void compile_buffer(const Buffer<> &buffer)
virtual bool promote_indices() const
Should indexing math be promoted to 64-bit on platforms with 64-bit pointers?
void visit(const GE *) override
void visit(const Variable *) override
void declare_intrin_overload(const std::string &name, const Type &ret_type, llvm::Function *impl, std::vector< Type > arg_types)
llvm::Value * codegen_dense_vector_load(const Load *load, llvm::Value *vpred=nullptr, bool slice_to_native=true)
Generate a basic dense vector load, with an optional predicate and control over whether or not we sho...
void visit(const Atomic *) override
void create_assertion(llvm::Value *condition, const Expr &message, llvm::Value *error_code=nullptr)
Codegen an assertion.
virtual Type upgrade_type_for_storage(const Type &) const
Return the type that a given Halide type should be stored/loaded from memory as.
void visit(const Shuffle *) override
void visit(const Allocate *) override=0
Generate code for an allocate node.
void visit(const Prefetch *) override
void visit(const Provide *) override
These IR nodes should have been removed during lowering.
virtual Type upgrade_type_for_arithmetic(const Type &) const
Return the type in which arithmetic should be done for the given storage type.
llvm::Value * normalize_fixed_scalable_vector_type(llvm::Type *desired_type, llvm::Value *result)
Ensure that a vector value is either fixed or vscale depending to match desired_type.
void visit(const Div *) override
llvm::StructType * halide_buffer_t_type
WarningKind
Warning messages which we want to avoid displaying number of times.
void visit(const EQ *) override
virtual int native_vector_bits() const =0
What's the natural vector bit-width to use for loads, stores, etc.
llvm::Value * match_vector_type_scalable(llvm::Value *value, llvm::Type *guide)
llvm::StructType * dimension_t_type
std::map< WarningKind, std::string > onetime_warnings
static std::unique_ptr< llvm::Module > compile_trampolines(const Target &target, llvm::LLVMContext &context, const std::string &suffix, const std::vector< std::pair< std::string, ExternSignature > > &externs)
virtual void compile_func(const LoweredFunc &func, const std::string &simple_name, const std::string &extern_name)
Compile a specific halide declaration into the llvm Module.
llvm::FunctionType * signature_to_type(const ExternSignature &signature)
Given a Halide ExternSignature, return the equivalent llvm::FunctionType.
llvm::Constant * create_string_constant(const std::string &str)
Put a string constant in the module as a global variable and return a pointer to it.
virtual llvm::Value * concat_vectors(const std::vector< llvm::Value * > &)
Concatenate a bunch of llvm vectors.
llvm::LLVMContext * context
llvm::Value * create_alloca_at_entry(llvm::Type *type, int n, bool zero_initialize=false, const std::string &name="")
Perform an alloca at the function entrypoint.
llvm::Value * match_vector_type_scalable(llvm::Value *value, llvm::Value *guide)
virtual std::string get_allocation_name(const std::string &n)
Get a unique name for the actual block of memory that an allocate node uses.
virtual bool use_soft_float_abi() const =0
virtual std::string mabi() const
void visit(const Evaluate *) override
std::map< std::string, std::vector< Intrinsic > > intrinsics
Mapping of intrinsic functions to the various overloads implementing it.
std::string mangle_llvm_type(llvm::Type *type)
Return type string for LLVM type using LLVM IR intrinsic type mangling.
void visit(const LE *) override
llvm::Value * codegen_buffer_pointer(const std::string &buffer, Type type, llvm::Value *index)
Generate a pointer into a named buffer at a given index, of a given type.
void visit(const NE *) override
void add_tbaa_metadata(llvm::Instruction *inst, std::string buffer, const Expr &index)
Mark a load or store with type-based-alias-analysis metadata so that llvm knows it can reorder loads ...
void visit(const And *) override
virtual bool use_pic() const
void scalarize(const Expr &)
Codegen a vector Expr by codegenning each lane and combining.
void visit(const StringImm *) override
virtual void codegen_vector_reduce(const VectorReduce *op, const Expr &init)
Compile a horizontal reduction that starts with an explicit initial value.
void codegen_asserts(const std::vector< const AssertStmt * > &asserts)
Codegen a block of asserts with pure conditions.
llvm::Function * get_llvm_intrin(const Type &ret_type, const std::string &name, const std::vector< Type > &arg_types, bool scalars_are_vectors=false)
Get an LLVM intrinsic declaration.
size_t get_requested_alloca_total() const
static std::unique_ptr< CodeGen_LLVM > new_for_target(const Target &target, llvm::LLVMContext &context)
Create an instance of CodeGen_LLVM suitable for the target.
virtual Type upgrade_type_for_argument_passing(const Type &) const
Return the type that a Halide type should be passed in and out of functions as.
void visit(const GT *) override
llvm::Value * fixed_to_scalable_vector_type(llvm::Value *fixed)
Convert an LLVM fixed vector value to the corresponding vscale vector value.
void visit(const Cast *) override
void visit(const Ramp *) override
void visit(const Broadcast *) override
void visit(const Mod *) override
llvm::Value * make_halide_type_t(const Type &)
Turn a Halide Type into an llvm::Value representing a constant halide_type_t.
void visit(const Call *) override
static void initialize_llvm()
Initialize internal llvm state for the enabled targets.
llvm::Value * simple_call_intrin(const std::string &intrin, const std::vector< llvm::Value * > &args, llvm::Type *result_type)
call_intrin does far too much to be useful and generally breaks things when one has carefully set thi...
void set_context(llvm::LLVMContext &context)
Tell the code generator which LLVM context to use.
void visit(const Store *) override
int get_vector_num_elements(const llvm::Type *t)
Get number of vector elements, taking into account scalable vectors.
llvm::Value * call_intrin(const Type &t, int intrin_lanes, llvm::Function *intrin, std::vector< Expr >)
llvm::Value * register_destructor(llvm::Function *destructor_fn, llvm::Value *obj, DestructorType when)
llvm::Value * codegen(const Expr &)
Emit code that evaluates an expression, and return the llvm representation of the result of the expre...
void optimize_module()
Run all of llvm's optimization passes on the module.
llvm::Value * codegen_buffer_pointer(llvm::Value *base_address, Type type, Expr index)
llvm::Value * sym_get(const std::string &name, bool must_succeed=true) const
Fetch an entry from the symbol table.
void visit(const ProducerConsumer *) override
virtual llvm::Value * shuffle_vectors(llvm::Value *a, llvm::Value *b, const std::vector< int > &indices)
Create an LLVM shuffle vectors instruction.
void visit(const LT *) override
void visit(const Load *) override
std::variant< NoMask, AllEnabledMask, llvm::Value * > MaskVariant
Predication mask using the above two types for special cases and an llvm::Value for the general one.
llvm::Value * convert_fixed_or_scalable_vector_type(llvm::Value *arg, llvm::Type *desired_type)
Convert between two LLVM vectors of potentially different scalable/fixed and size.
virtual llvm::Value * slice_vector(llvm::Value *vec, int start, int extent)
Take a slice of lanes out of an llvm vector.
llvm::Function * declare_intrin_overload(const std::string &name, const Type &ret_type, const std::string &impl_name, std::vector< Type > arg_types, bool scalars_are_vectors=false)
Declare an intrinsic function that participates in overload resolution.
bool inside_atomic_mutex_node
Are we inside an atomic node that uses mutex locks? This is used for detecting deadlocks from nested ...
void visit(const FloatImm *) override
void visit(const IntImm *) override
Generate code for various IR nodes.
void function_does_not_access_memory(llvm::Function *fn)
Add the appropriate function attribute to tell LLVM that the function doesn't access memory.
llvm::Value * call_intrin(const Type &t, int intrin_lanes, const std::string &name, std::vector< Expr >)
Generate a call to a vector intrinsic or runtime inlined function.
llvm::BasicBlock * get_destructor_block()
Retrieves the block containing the error handling code.
virtual void init_module()
Initialize the CodeGen_LLVM internal state to compile a fresh module.
llvm::Value * get_user_context() const
The user_context argument.
virtual std::string mattrs() const =0
void visit(const Realize *) override
void visit(const VectorReduce *) override
void visit(const IfThenElse *) override
size_t requested_alloca_total
A (very) conservative guess at the size of all alloca() storage requested (including alignment paddin...
Expr wild_u1x_
Some wildcard variables used for peephole optimizations in subclasses.
llvm::StructType * pseudostack_slot_t_type
llvm::Type * llvm_type_of(llvm::LLVMContext *context, Halide::Type t, int effective_vscale) const
Get the llvm type equivalent to a given halide type.
llvm::Value * scalable_to_fixed_vector_type(llvm::Value *scalable)
Convert an LLVM vscale vector value to the corresponding fixed vector value.
llvm::Value * call_intrin(const llvm::Type *t, int intrin_lanes, llvm::Function *intrin, std::vector< llvm::Value * >, bool is_reduction=false)
bool sym_exists(const std::string &name) const
Test if an item exists in the symbol table.
llvm::Value * match_vector_type_scalable(llvm::Value *value, VectorTypeConstraint constraint)
Make sure a value type has the same scalable/fixed vector type as a guide.
void visit(const Free *) override=0
Generate code for a free node.
llvm::Value * shuffle_vectors(llvm::Value *v, const std::vector< int > &indices)
Shorthand for shuffling a single vector.
void visit(const Add *) override
void visit(const Block *) override
virtual bool supports_call_as_float16(const Call *op) const
Can we call this operation with float16 type? This is used to avoid "emulated" equivalent code-gen in...
void visit(const UIntImm *) override
void visit(const LetStmt *) override
llvm::Type * void_t
Some useful llvm types.
llvm::Value * call_overloaded_intrin(const Type &result_type, const std::string &name, const std::vector< Expr > &args)
Call an overloaded intrinsic function.
virtual llvm::Value * interleave_vectors(const std::vector< llvm::Value * > &)
Implementation of the intrinsic call to interleave_vectors.
llvm::Type * get_vector_type(llvm::Type *, int n, VectorTypeConstraint type_constraint=VectorTypeConstraint::None) const
A base class for algorithms that need to recursively walk over the IR.
Definition IRVisitor.h:19
virtual void visit(const IntImm *)
A common pattern when traversing Halide IR is that you need to keep track of stuff when you find a Le...
Definition Scope.h:94
A halide module.
Definition Module.h:142
A reference-counted handle to a parameter to a halide pipeline.
Definition Parameter.h:40
This file defines the class FunctionDAG, which is our representation of a Halide pipeline,...
LinkageType
Type of linkage a function in a lowered Halide module can have.
Definition Module.h:52
std::unique_ptr< llvm::Module > codegen_llvm(const Module &module, llvm::LLVMContext &context)
Given a Halide module, generate an llvm::Module.
std::map< std::string, std::string > MetadataNameMap
Definition Module.h:138
signed __INT32_TYPE__ int32_t
A fragment of Halide syntax.
Definition Expr.h:258
The sum of two expressions.
Definition IR.h:56
Allocate a scratch area called with the given name, type, and size.
Definition IR.h:371
Logical and - are both expressions true.
Definition IR.h:175
If the 'condition' is false, then evaluate and return the message, which should be a call to an error...
Definition IR.h:294
Lock all the Store nodes in the body statement.
Definition IR.h:961
A sequence of statements to be executed in-order.
Definition IR.h:442
A vector with 'lanes' elements, in which every element is 'value'.
Definition IR.h:259
A function call.
Definition IR.h:490
The actual IR nodes begin here.
Definition IR.h:30
Type indicating mask to use is all true – all lanes enabled.
Description of an intrinsic function overload.
Intrinsic(Type result_type, std::vector< Type > arg_types, llvm::Function *impl)
Type indicating an intrinsic does not take a mask.
Support for generating LLVM vector predication intrinsics ("@llvm.vp.*" and "@llvm....
std::optional< size_t > mangle_index
VPArg(llvm::Value *value, std::optional< size_t > mangle_index=std::nullopt, int32_t alignment=0)
VPResultType(llvm::Type *type, std::optional< size_t > mangle_index=std::nullopt)
The ratio of two expressions.
Definition IR.h:83
Is the first expression equal to the second.
Definition IR.h:121
Evaluate and discard an expression, presumably because it has some side-effect.
Definition IR.h:476
Floating point constants.
Definition Expr.h:236
A for loop.
Definition IR.h:819
Free the resources associated with the given buffer.
Definition IR.h:413
Is the first expression greater than or equal to the second.
Definition IR.h:166
Is the first expression greater than the second.
Definition IR.h:157
An if-then-else block.
Definition IR.h:466
Integer constants.
Definition Expr.h:218
Is the first expression less than or equal to the second.
Definition IR.h:148
Is the first expression less than the second.
Definition IR.h:139
A let expression, like you might find in a functional language.
Definition IR.h:271
The statement form of a let node.
Definition IR.h:282
Load a value from a named symbol if predicate is true.
Definition IR.h:217
Definition of a lowered function.
Definition Module.h:101
The greater of two values.
Definition IR.h:112
The lesser of two values.
Definition IR.h:103
The remainder of a / b.
Definition IR.h:94
The result of modulus_remainder analysis.
The product of two expressions.
Definition IR.h:74
Is the first expression not equal to the second.
Definition IR.h:130
Logical not - true if the expression false.
Definition IR.h:193
Logical or - is at least one of the expression true.
Definition IR.h:184
Represent a multi-dimensional region of a Func or an ImageParam that needs to be prefetched.
Definition IR.h:923
This node is a helpful annotation to do with permissions.
Definition IR.h:315
This defines the value of a function at a multi-dimensional location.
Definition IR.h:354
A linear ramp vector node.
Definition IR.h:247
Allocate a multi-dimensional buffer of the given type and size.
Definition IR.h:427
Reinterpret value as another type, without affecting any of the bits (on little-endian systems).
Definition IR.h:47
A ternary operator.
Definition IR.h:204
Construct a new vector by taking elements from another sequence of vectors.
Definition IR.h:855
A reference-counted handle to a statement node.
Definition Expr.h:427
Store a 'value' to the buffer called 'name' at a given 'index' if 'predicate' is true.
Definition IR.h:333
String constants.
Definition Expr.h:245
The difference of two expressions.
Definition IR.h:65
Unsigned integer constants.
Definition Expr.h:227
A named variable.
Definition IR.h:772
Horizontally reduce a vector to a scalar or narrower vector using the given commutative and associati...
Definition IR.h:979
A struct representing a target machine and os to generate code for.
Definition Target.h:19
Types in the halide type system.
Definition Type.h:283
int error_code